The menu was intended to be hidden when the mouse is moved away, but it actually hides

I'm facing an issue with my button and menu functionality. Even though I have coded the menu to hide itself when the mouse leaves, it hides before the mouse even goes over it. Any suggestions on how to resolve this?

function showMenu() {
  var menuBar = document.getElementById("menu");

  menuBar.style.display = "block";

}

function hideMenu() {
  document.getElementById("menu").style.display = "none";
}
<a id="menu_button" onmouseover="showMenu()"><img src="https://i.imgur.com/mRIyhW8.png" class="menu_button" onmouseover="this.src='https://i.imgur.com/zSPpoVX.png'" onmouseout="this.src='https://i.imgur.com/mRIyhW8.png'" /></a>

<div id="menu" onmouseout="hideMenu()">
  <ul>
    <li>HOME</li>
    <li>PORTFOLIO</li>
    <li>ABOUT</li>
  </ul>
</div>

UPDATE Resolved the issue by adding a z-index: 2; in my CSS. Appreciate your assistance.

Answer №1

It is recommended to utilize the mouseleave function because:

The mouseout event is activated when the mouse pointer exits any child elements within the selected element.

Update:

  1. Adjusted the dimensions of the menu_button to prevent unintended activation outside of the image.
  2. Implemented CSS on #menu to initialize it in a concealed state.
  3. Integrated a mouseleave action on menu_button to hide the menu when hovering away from the image.

document.getElementById("menu_button").addEventListener('mouseover', function() {
  document.getElementById("menu").style.display = "block";
});

document.getElementById("menu").addEventListener('mouseover', function() {
  document.getElementById("menu").style.display = "block";
});

document.getElementById("menu").addEventListener('mouseleave', function() {
  document.getElementById("menu").style.display = "none";
});

document.getElementById("menu_button").addEventListener('mouseleave', function() {
  document.getElementById("menu").style.display = "none";
});
#menu_button {
  display: block;
  width: 50px;
  height: 50px;
}

#menu_button img:hover {
  opacity: 0.8;
}

#menu {
  border: solid 1px;
  display: none;
 }
<a id="menu_button"><img src="https://i.imgur.com/mRIyhW8.png" class="menu_button" /></a>

<div id="menu">
  <ul>
    <li>HOME</li>
    <li>PORTFOLIO</li>
    <li>ABOUT</li>
  </ul>
</div>

Answer №2

The onmouseout event is activated when the mouse moves over the UL element. It can be challenging to address this issue using only pure javascript, but fortunately Jquery provides convenient methods like mouseenter and mouseleave.

    $("#menu_button").mouseenter(function () {
        $("#menu").show();
    });
    $("#menu").mouseleave(function () {
        $(this).hide();
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What sets $vm.user apart from $vm.$data.user in Vuejs?

When you need to retrieve component data, there are two ways to do so: $vm.user and $vm.$data.user. Both methods achieve the same result in terms of setting and retrieving data. However, the question arises as to why there are two separate ways to access ...

Deleting a specific row within a Material UI DataGrid in Reactjs: Tips and tricks

As I embark on this React project, things are progressing smoothly. However, a challenge has arisen. The functionality I aim for is as follows: When the checkbox in a row is clicked, I want that particular row to be deleted. For instance, selecting checkb ...

The controller failed to return a value when utilizing the factory

I am attempting to pass a value from my view to the controller using a function within the ng-click directive. I want to then use this value to send it to my factory, which will retrieve data from a REST API link. However, the value I am sending is not ret ...

Using a variable to store the value of the id attribute in HTML code

How can I dynamically add an ID attribute to an HTML element using a variable declared in JavaScript? Using jQuery var table_row = $('table').find('tr#' + pid); var name = table_row.find('td:nth-child(1)').html(); table_ ...

A guide on converting character objects to strings

Presented below is an array of characters: Resource {0: "-", 1: "-", 2: "-", 3: "-", 4: "-", 5: "B", 6: "E", 7: "G", 8: "I", 9: "N", 10: " ", 11: "C", 12: "E", 13: "R", 14: "T", 15: "I", .... } I am looking to convert it into the following format: --- ...

A step-by-step guide on using Javascript to transform images into text

Hey there! I'm looking for some help to convert an image into text. The idea is that when someone uploads an image and hits the "Submit" button, the text from the image should display in a textarea below. However, the code I've been working on do ...

Issues arise when attempting to determine the accurate dimensions of a canvas

Looking at my canvas element: <canvas id='arena'></canvas> This Element is set to fill the entire website window. It's contained within a div Element, both of which are set to 100% size. I attempted running this script: var c ...

What is the best way to determine if the form has been submitted?

I am working on a React form and need to determine when the form has been successfully submitted in order to trigger another request in a separate form. const formRef = React.useRef<HTMLFormElement>(null); useEffect(() => { if (formRef &a ...

What methods are most effective when utilizing imports to bring in components?

Efficiency in Component Imports --Today, let's delve into the topic of efficiency when importing components. Let's compare 2 methods of importing components: Method 1: import { Accordion, Button, Modal } from 'react-bootstrap'; Meth ...

What does Angular classify as a watcher?

What qualifies as "watchers" within Angular? Are watchers the only type of monitoring mechanism, or do other Angular elements like ngModel also serve as watchers? Am I overlooking something crucial? For example, do watchers play a role in enabling directi ...

`I'm having trouble retrieving radio button values in jQuery's ajaxForm.`

I'm facing an issue with a form that is bound to a JQuery Form (AjaxForm) object. Within the form, I have some radio buttons: <input type="radio" id="dialog_stranka_dodajuredi_tip_fizicna" name="dialog_stranka_dodajuredi_tip" value="2" /> Sele ...

What is preventing me from using javascript setInterval with a function in a separate external file?

Everything is running smoothly with this code snippet...an alert pops up every 10 seconds <script type='text/javascript'> function letsTest(){ alert("it works"); } var uptimeId = window.setInterval(letsTest, 10000); < ...

What is the best way to utilize localStorage along with AJAX in php in order to update my database effectively?

I am facing a challenge where I need to utilize a value stored in the localStorage of my browser within a PHP file in order to update data in my database. Despite knowing that I require ajax for this task, I have been unable to make it work as intended. T ...

I am searching for a straightforward Rails sample that incorporates Ajax

Currently, I am on a quest to find a solid demonstration of how AJAX and JSON interact with Rails. I have a Rails application that relies on standard forms and I am looking to enhance it with some ajax functionality. Unfortunately, I haven't come acro ...

"Possible Reasons for Jquery Not Displaying JSON Data When Retrieving from W

I have created a basic WCF method that is returning the correct values, but for some reason it is showing a status code of 200. $.ajax({ url: "http://localhost:60770/Service.svc/GetContacts?calback=?", type: "POST", dataType: " ...

Modify the JQuery change function depending on whether the 'select' exceeds or falls below a specified value

Currently, I am facing a challenge that I believe is not too far from being solved. Essentially, I have an Age Verification form that only displays the year unless the year would make a difference in meeting the age requirement, in which case the day and ...

Using div elements to mimic the layout of tables with row spans

<div class="container"> <div class="box1">1</div> <div class="box2">2</div> <div class="box3">3</div> </div> .box1 { border: 1px solid red; float: left; width: 20px; } .box2, .box3 { ...

EJS: Warning when the "<%= %>" tag is used multiple times within the code

I am currently working on incorporating EJS with Node.js and Express.js. I have defined an array variable called "kindOfDay" containing the names of days as strings, such as "Sun", "Mon"... Within the EJS views folder, there is a file named list.ejs. The i ...

Conceal header and footer bar in Jquery Datatable theme

I need assistance in removing the header/footer bar from this table Here is a visual representation of what I am looking to remove: The jQuery code for this table: $(document).ready(function() { var oTable = $('#tableSmooth').dataTable({ ...

Tips for displaying an arrow icon that points up or down when clicking on a table header in Vue.js

I am currently working on a listing page where data is fetched using Laravel. The issue I am facing is related to sorting functionality when clicking on the table headings (<th>). The desired behavior is for arrow marks to indicate ascending or desce ...