So I have a drop-down menu that shows on a click, as per business requirements. The menu becomes hidden again after you mouse away from it.
But now I am being asked to have it stay in place until user clicks anywhere on the document. How can this be accomplished?
This is a simplified version of what I have now:
$(document).ready(function() {
$("ul.opMenu li").click(function(){
$('#MainOptSubMenu',this).css('visibility', 'visible');
});
$("ul.opMenu li").mouseleave(function(){
$('#MainOptSubMenu',this).css('visibility', 'hidden');
});
});
<ul class="opMenu">
<li id="footwo" class="">
<span id="optImg" style="display: inline-block;"> <img src="http://localhost.vmsinfo.com:8002/insight/images/options-hover2.gif"/> </span>
<ul id="MainOptSubMenu" style="visibility: hidden; top: 25px; border-top: 0px solid rgb(217, 228, 250); background-color: rgb(217, 228, 250); padding-bottom: 15px;">
<li>some</li>
<li>nav</li>
<li>links</li>
</ul>
</li>
</ul>
I tried something like this $('document[id!=MainOptSubMenu]').click(function()
thinking it would trigger on anything that wasnt the menu, but it didnt work.
I found a variant of Grsmto's solution and Dennis' solution fixed my issue.
The answer is right, but it will add a listener that will be triggered every time a click occurs on your page. To avoid that, you can add the listener for just one time :
Edit: if you want to avoid the
stopPropagation()
on the initial button you can use thisThe
stopPropagation
options are bad because they can interfere with other event handlers including other menus that might have attached close handlers to the HTML element.Here is a simple solution based on user2989143's answer:
I use this solution with multiple elements with the same behavior in the same page:
stopPropagation() is a bad idea, this breaks standard behaviour of many things, including buttons and links.
I find it more useful to use mousedown-event instead of click-event. The click-event doesn't work if the user clicks on other elements on the page with click-events. In combination with jQuery's one() method it looks like this:
If using a plugin is ok in you case, then I suggest Ben Alman's clickoutside plugin located here:
its usage is as simple as this:
hope this helps.