Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hide div on mouseout

Tags:

html

jquery

I saw a lot of posts on this item, but couldn't find the right solution. Sorry if it's already answered somewhere.

What I want: I have a DIV with my menu items, that opens when the click event is fired of an href element. Now I wanna hide the menu, when the mouse is out of the DIV element and is not above the href element. So far I can only close it when I click 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!

like image 251
Jorelie Avatar asked Jul 07 '11 20:07

Jorelie


2 Answers

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

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

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

like image 89
NakedBrunch Avatar answered Sep 24 '22 02:09

NakedBrunch


if i understand the "is not above the href element" piece, you want the menu to stay visible when mousing off of div#menudiv, but still moused over a#menu_opener ??

if that's the case, i'd wrap the entire thing in a unqiue div and target that. and use mouseleave over mouseout.

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

so, your HTML becomes:

<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 would be something like:

$("#menu_opener").click(function () {
  if ($("#menudiv").is(":hidden")) {
      $("#menudiv").slideDown("slow");
  } else {
      $("#menudiv").hide();
  }
});
$("#menu_container").mouseleave(function(){
    $('#menudiv').hide();
});
like image 44
Marc Smith Avatar answered Sep 26 '22 02:09

Marc Smith