Search code examples
jqueryeventsevent-bubbling

encasing div and anchor link binded to same event


im having trouble figuring out how to bind mouseout() to my entire nav bar including the links.

when a user hovers over a link in #nav a sub menu is shown. all is well there.

what i want to do is fadeOut that sub menu when the user hovers out of the entire #nav.

my code for the mouseout:

$('#nav').mouseout(function() {
  setTimeout(function() {
   //$('.sub-link').fadeOut();
  }, 2000);
});

when i hover over an anchor link which resides in #nav, i see the sub-menu. then i guess the mouseout() even fires and the sub-menu fades out. is there anyway to have the #nav and any anchor links within it to act as one?

i'd paste my markup but even indenting it 4 spaces still shows as rendered html..

sample page at: http://chrisparaiso.com/test/


Solution

  • The mouseleave() should be what you need:

    $('#nav').mouseleave(function() {
      setTimeout(function() {
       $('.sub-link').fadeOut();
      }, 2000);
    });
    

    From the documentation:

    The mouseleave event, on the other hand, only triggers its handler when the mouse leaves the element it is bound to, not a descendant.

    You are right that mouseout is triggered if the cursor is over an element inside the element you bound the event to. But mouseleave is really only triggered when the cursor leaves the while element.

    This example demonstrates very the the differences between mouseleave() and mouseout().