views:

1822

answers:

2

I'm working on a jQuery drop-down menu that fades in when you hover on the top-level items. I want to set it so that when you move the mouse away the menu doesn't disappear instantly. I have this code:

$(document).ready(function(){
  $('ul#menu > li').hover(
    // mouseover
    function(){
      $(this).find('>ul').fadeIn('fast');
    },
    // mouseout
    function(){
      setTimeout( function(){
        alert('fadeout');
        $(this).find('>ul').fadeOut('fast')
        }, 1000 );
    }  
  );
});

After a second the alert happens, but the menu isn't faded out.

+2  A: 

window.setTimeout(), so this refers to the window object.

// mouseout
function(){
  var el=this;
  setTimeout( function(){
    alert('fadeout');
    $(el).find('>ul').fadeOut('fast')
    }, 1000 );
}
Decided to go with a solution similar to this, thanks!
DisgruntledGoat
+2  A: 

Have a look at hoverIntent. It'll give you greater control of the behaviour of the mouseover/mouseout events by configuration:

var config = {    
     sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
     interval: 200, // number = milliseconds for onMouseOver polling interval    
     timeout: 500, // number = milliseconds delay before onMouseOut    
};

$(document).ready(function(){
  $('ul#menu > li').hoverIntent(
    // mouseover
    function(){
      $(this).find('>ul').fadeIn('fast');
    },
    // mouseout
    function(){
       $(this).find('>ul').fadeOut('fast');
    }  
  );
});
karim79
This looks pretty cool, thanks! I have one problem though: I want the timeout when I move away from the menu completely, but if I move from one menu item to the next I want to turn the old menu off instantly - is that possible?
DisgruntledGoat
Use .stop(true,true): http://docs.jquery.com/Effects/stop
Hmm, not sure if that's what I need. What I meant is I want to remove the delay before each menu appears, if the menu is already open. So the very first mouseover would have a short delay (to prevent opening the menu when brushing past). But if a menu is open, moving to the next menu along would display it instantly without the delay.
DisgruntledGoat
You can check the state of the menu (by the styles or checking if its animating ":animated" pseudo-selector) or store a boolean flag. A boolean flag may be faster and simpler to implement.