tags:

views:

4703

answers:

1

The following code displays a sub-menu when you hover over a menu item. Since its using a timer, if you don't select the sub-menu item fast enough, the sub-menu items disappear. I would rather have it highlite the menu option it is on and keep the sub-menu items until you hover over or click another main menu item:

$(document).ready(function(){ Nifty("#menu a","small top transparent"); Nifty("#outcontent","medium bottom transparent");

function hideSubMenu() {
 $("#sub-menu-content").fadeOut('slow');
 hideSubMenu.timeout = 0;
}

$('#menu a').hover(function() { //start function when any link is clicked
 if (hideSubMenu.timeout) clearTimeout(hideSubMenu.timeout);
 hideSubMenu.timeout = 0;
 $("#sub-menu-content").hide();

 var html = '<ul>' + $(this).next('ul.sub-menu').html() + '</ul>&nbsp;';
 $("#sub-menu-content").html(html); //show the html inside .content div
 $("#sub-menu-content").fadeIn('fast'); //animation
},function(){
 hideSubMenu.timeout = setTimeout(hideSubMenu, 800);
}); //close click(

$('#sub-menu-content').hover(function() {
 if (hideSubMenu.timeout) clearTimeout(hideSubMenu.timeout);
 hideSubMenu.timeout = 0;
},function(){
 hideSubMenu.timeout = setTimeout(hideSubMenu, 800);
}); //close click(
}); //close $(

To see it in action:

http://cruisecontrolledmarketing.com/test/welcome/login user: member password: rebmem

Thank you!

+2  A: 

Rather than hacking something up yourself, how about checking out the hoverIntent plugin?

ajm
I'll check it out. I've never seen that before.
Jon Schenk
I recommend it. We use it in production on sites all the time. Nice and easy to configure, and should do exactly what you need it to.
ajm
I'm trying to get it to work.. would i just replace the hover events? i.e. $('#menu a').hover(function() { would become $("#menu a").hoverIntent( config, function() ) {I also found jquery.event.hover-1.0.js - its supposed to be "better" than hoverIntent. I'm checking both out.
Jon Schenk
Yeah, you'd replace .hover() with .hoverIntent(). I've found that looking at the source of their examples points you in the right direction better than their documentation. I haven't checked out jquery.event.hover, but, if you do, let me know what you think.
ajm