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.

DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290

2 Answers2

3

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

// mouseout
function(){
  var el=this;
  setTimeout( function(){
    alert('fadeout');
    $(el).find('>ul').fadeOut('fast')
    }, 1000 );
}  
user120242
  • 14,918
  • 3
  • 38
  • 52
3

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
  • 339,989
  • 67
  • 413
  • 406
  • 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 Sep 22 '09 at 01:42
  • 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 Sep 22 '09 at 02:29
  • 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. – user120242 Sep 22 '09 at 04:59