I have a button and a menu. The button on mouse over shows the menu. I've coded when the mouse leaves the menu to hide itself, but it hides before the mouse goes over it. Help?
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>
EDIT Adding a z-index: 2; in my css solved the problem. Thank you for your time.
onmouseout event is triggered when the mouse over the UL element. It it complex to solve this problem with pure javascript. Jquery has mouseenter and mouseleave methods.
$("#menu_button").mouseenter(function () {
$("#menu").show();
});
$("#menu").mouseleave(function () {
$(this).hide();
});
You need to use mouseleave
because:
The mouseout event triggers when the mouse pointer leaves any child elements as well the selected element.
Update:
menu_button
to avoid triggering outside the image. mouseleave
to menu_button
to hide when leaving 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.