JQuery hide div on mouseout

I saw a lot of posts about this item, but could not find the right solution. Sorry if he already answered somewhere.

What I want: I have a DIV with my menu items that opens when the click event fires from the href element. Now I want to hide the menu when the mouse is outside the DIV element and not above the href element. For now, I can close it only when I click on the href element.

So my jQuery looks like this:

 $("#menu_opener").click(function () { if ($("#menudiv").is(":hidden")) { $("#menudiv").slideDown("slow"); } else { $("#menudiv").hide(); } }); 

And my HTML looks like this:

 <div> <a href="#" id="menu_opener">Menu</a> </div> <div id="menudiv" style="position: fixed; background-color: white; display: none;"> <a href="#" id="A1">Page 1</a><br /> <a href="#" id="A2">Page 2</a><br /> <a href="#" id="A3">Page 3</a><br /> </div> 

Thanks in advance!

+7
source share
3 answers

You can save the HTML as is and simply add the following:

 $("#menudiv").mouseleave(function(){ $(this).hide(); }); 

jsFiddle: http://jsfiddle.net/5SSDz/

+16
source

if I understand that the element is โ€œnot higher than the href elementโ€, do you want the menu to remain visible when the div # menudiv is turned off, but still mussed over # menu_opener ??

if that happens, I would wrap it all in an unqiue div and target. and use mouseleave for the mouse.

http://api.jquery.com/mouseleave/

so your HTML will look like this:

 <div id="menu_container"> <div> <a href="#" id="menu_opener">Menu</a> </div> <div id="menudiv" style="position: fixed; background-color: white; display: none;"> <a href="#" id="A1">Page 1</a><br /> <a href="#" id="A2">Page 2</a><br /> <a href="#" id="A3">Page 3</a><br /> </div> </div> 

and your script will look something like this:

 $("#menu_opener").click(function () { if ($("#menudiv").is(":hidden")) { $("#menudiv").slideDown("slow"); } else { $("#menudiv").hide(); } }); $("#menu_container").mouseleave(function(){ $('#menudiv').hide(); }); 
+6
source

Edit: Sorry, misread the question for the first time. I had to do this a couple of times, and I always moved the menu to a pixel so that it overlaps the href element. And then show / hide the menu if the href elements OR href hang.

 $("#menu_opener, #menudiv").hover( function(){ $("#menudiv").show(); }, function(){ $("#menudiv").hide(); } ); 

And set the top property for the menudal style so that it moves up and overlaps the href.

 <div> <a href="#" id="menu_opener">Menu</a> </div> <div id="menudiv" style="position: fixed; top: -1px; background-color: white; display: none;"> <a href="#" id="A1">Page 1</a><br /> <a href="#" id="A2">Page 2</a><br /> <a href="#" id="A3">Page 3</a><br /> </div> 
+4
source

All Articles