0

I have a menu link, that when hovered, shows a div#options under it. The issue is that I want to hide #options again when the mouse leaves it, but also if when it leaves the link element.

I thought the best way to do this was: on the link's hover-out function, see if the cursor is on top of #options, if it is, return false, else proceed to hiding it again.

Something like this

 $('#menu-link').hover(function() {
        $('#options').slideDown()
    }, function() {
        // Perhaps only do this if mouse is NOT on top of #options?
        $('#options').slideUp()
    });

But how can I detect which element the cursor is on?

or even, is there a better way of doing this?

very simple jsfiddle describing this is here: http://jsfiddle.net/N6kwn/5/

sqram
  • 7,069
  • 8
  • 48
  • 66

3 Answers3

2

...or even, is there a better way of doing this?

Yes there is, but you'll need to change your markup a bit. This is the cleanest way I can think of:

HTML:

<ul id="options">
  <li><a href="">A menu link</a>
    <ul>
      <li><a href="">Option A</a></li>
      <li><a href="">Option B</a></li>
      <li><a href="">Option C</a></li>
    </ul>
  </li>
</ul>

CSS:

#options,
#options ul {
  float: left;
  list-style: none;
  padding: 0;
  background: black;
}
#options a {
  display: block;
  text-decoration: none;
  color: yellow;
  padding: .5em 1em;
}
#options ul {
  position: absolute;
  display: none;
  min-width: 200px;
}

JavaScript:

$('#options').hover(function(){
  $(this).find('ul').stop(1).slideToggle();
});

Demo: http://jsbin.com/ehalon/1/edit

elclanrs
  • 92,861
  • 21
  • 134
  • 171
1

You just need to move the closing </div> tag so that the submenu is enclosed in the menu...

http://jsfiddle.net/N6kwn/6/

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
0

Please refer to http://api.jquery.com/category/events/mouse-events/

Specifically: mouseover, mouseout

ilan berci
  • 3,883
  • 1
  • 16
  • 21