Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click outside menu to close in jquery

Tags:

jquery

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.

like image 871
George Avatar asked May 19 '10 19:05

George


1 Answers

Take a look at the approach this question used:

How do I detect a click outside an element?

Attach a click event to the document body which closes the window. Attach a separate click event to the window which stops propagation to the document body.
$('html').click(function() {   //Hide the menus if visible });  $('#menucontainer').click(function(event){     event.stopPropagation(); }); 

like image 143
Jon W Avatar answered Oct 21 '22 08:10

Jon W