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

Tap and hold with Zepto

I've been on the hunt for a Zepto plugin that can handle a longClick event. While Zepto already supports longTap, which is perfect for mobile devices, I need something specifically for desktop browsers when a user clicks and holds. It's also impo ...

Changing an array into an object in JavaScript without rearranging the keys

I have a collection { 1: {id: 1, first: 1, last: 5} 2: {id: 2, first: 6, last: 10} 3: {id: 3, first: 11, last: 15} } My goal is to reverse the order of items without rearranging the keys so that it looks like this: { 1: {id: 3, first: 11, last: 15} 2: { ...

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

jQuery can be used to relocate buttons on a webpage

When the Contact button is clicked, how can I move the Close button below #panel? It's currently fixed in position. Here's my demonstration: https://jsfiddle.net/25u78gff/ jQuery('.sub-menu').addClass('dropdown-menu'); jQ ...

table rows are styled with hover effects and alternating colors using CSS

Styles for even and odd table rows are set, but hovering over the table rows is not working. Test it out here: http://jsfiddle.net/w7brN/ CSS style : #table_even tr:hover { background-color:#fffbae!important; } /* hover effect */ #table_even tr:nth-ch ...

The path specified as "react-native/scripts/libraries" does not exist in the file

I've been troubleshooting an error on Github - https://github.com/callstack/react-native-fbads/issues/286. After cloning the repository and running it, I discovered that the error persisted. I am currently updating packages to investigate why this rec ...

Using the React JS useState hook to toggle the state of a JSON object containing an array when a checkbox is clicked

When I submit my state as a stringified variable from a form to a POST request via a lamda server, it gets parsed and sent to sendgrid for templating. To loop over specific parts (multiple checkboxes) in JSON format, each with the same key but different va ...

Elevate the expanded card above the others on hover instead of displacing them downward

I'm working on a grid of cards where hovering over one card expands the bottom section to reveal more content. The issue is, when it expands, it pushes all other cards down. What I actually want is for it to overlay on top of the card below it. Here ...

Style the CSS exclusively to the expanded menu section

I need help with applying CSS rules to my navbar menu without affecting the collapsed menu. I came across a solution here and tried using this code: @media (min-width: 980px) { /* your conditional CSS*/ } However, the issue arises when my browser win ...

Removal based on specific conditions upon losing focus

Here is the HTML code snippet that I am working with: <input type="text" id="myText"> <div id="myDiv"> I want to achieve a specific functionality where, when the user focuses out of the text field, #myDiv should be removed only if the user ha ...

I noticed that my WordPress website is loading both jQuery Migrate and jQuery version 1.10.2. Can you explain the difference between the two versions?

As I'm reviewing site performance checklists, I've observed that my WordPress website is loading both jQuery-migrate and jQuery 1.10.2. Is it necessary to have both, and what distinguishes them? ...

Unable to successfully submit a form using PHP

I am currently working on a PHP page that retrieves data from MySQL. The goal is to fetch a list of objects from the database, display each object in a separate form for editing, and then save only the edited values. However, I am encountering difficulties ...

Is it feasible to develop a Grafana datasource plugin that does not rely on an external backend system?

I am in the process of developing a Grafana datasource plugin that operates independently without relying on an external backend. My plugin is based on the simple-json datasource plugin available at: https://github.com/grafana/simple-json-datasource In a ...

A guide to implementing offline.js or online.js alongside a submit button

I am looking for a way to check network connection only when the user presses the SUBMIT button, without constantly monitoring for internet connectivity. After researching websites and Stack Overflow questions for weeks, I have not found a satisfactory sol ...

Exploring object properties within arrays and nested objects using ReactJS

Within the react component PokemonInfo, I am looking to extract the stats.base_stat value from the JSON obtained from https://pokeapi.co/api/v2/pokemon/1/. The issue lies in the fact that base_stat is nested inside an array called stats. My assumption is t ...

Could someone assist me in figuring out the reason behind my fetch method sending undefined values?

Looking for some assistance with my fetch implementation issue. I am currently working on integrating stripe into my online grocery store website utilizing a node.js server with express, and ejs for frontend integration. The client-side JavaScript uses a f ...

My CSS content seems to be fitting correctly, but it appears larger than anticipated. Where have I gone

I've been working on customizing my webpage for mobile phones, but I've encountered an issue. When I use the inspect tool in Chrome to make the "screen" smaller, the webpage itself appears smaller but the body element size remains unchanged, as i ...

Achieving data synchronization and sequencing with AngularJS promises at a 1:1 ratio

Concern I am facing challenges with AngularJS promise synchronization and sequencing as my app expands across multiple controllers and services. In this scenario, I have an articles controller named ArticleController along with a related service named Art ...

Learn how to incorporate PHP7 code into your HTML file through the use of .htaccess configurations

I have a Linux server with PHP 7.* installed. I want to embed PHP code into HTML files, but currently it just renders the PHP code on the webpage. I've tried adding the following code to my .htaccess file, but it doesn't seem to be working: AddH ...

Issue encountered while compiling ReactJs: Unexpected token error found in App.js

I executed the commands below. npx create-react-app github-first-app npm install --save react-tabs npm i styled-components npm install git-state --save using the following code files App.js import React from "react"; import Layout from " ...