views:

95

answers:

2

Hi guys,

I'm a complete absolute jQuery noob. I've been following a tutorial to add a CSS/jQuery navigation menu to my site, and I got it working.. The only thing I would like to see added is a small delay on Mouse out, because the dropdown menu is disappearing instantly when you mouse out which makes the menu a bit annoying to use. Here's my script:

function mainmenu(){
$(" .top-menu ul ").css({display: "none"}); // Opera Fix
$(" .top-menu li").hover(function(){
  $(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
  },function(){
  $(this).find('ul:first').css({visibility: "hidden"});
  });
}

 $(document).ready(function(){
 mainmenu();
});

Would anyone be so kind to add the needed code to this script. I'll promise to study how you've done it, so I actually learn from it ;-D

+4  A: 

You could do something like this, giving it a 500ms delay:

function mainmenu(){
  $(".top-menu ul ").hide();
  $(".top-menu li").hover(function() {
    clearTimeout($.data(this, 'timeout'));
    $(this).find('ul:first').show(400);
  }, function() {
    $.data(this, 'timeout', setTimeout($.proxy(function() { 
       $(this).find('ul:first').hide();
    }, this), 500));
  });
}
$(mainmenu);

This adds a 500 ms delay via setTimeout() and just stores the timer id with the element using $.data(), when hovering back in the element, it'll clear the timeout and won't run it again until you over out...so you have to be off the element for 500ms for it to hide.

Or, do something very similar with the hoverIntent plugin which is for just this problem.

Nick Craver
+1  A: 
$(" .top-menu li").hover(function(){
    $(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
},function(){

    // Note here...
    setTimeout(function(){
        $(this).find('ul:first').css({visibility: "hidden"});
    }, 2000);
    // 2000 is a delay time in milliseconds, change it

});
Otar
You have to store the timeout ID...what if I hovered *back* into the element? It'll hide in 2seconds regardless of if I'm actively using it :) Also `this` won't be what you want it to be in the function, you have to set the context of the closure or pass a reference to the element.
Nick Craver
Thanks for the quick response guys.. the codes does do something, but now the menu stays open even when I leave the navigation section. Any ideas ? :)
Bowe Frankema