Saturday, May 10, 2008

jQuery drop down menu delay (setTimeout)

posted by Alex Grande
To create a navbar with a subnav (drop down menu for instance) with a delay before closing using jQuery (jQ) follow this code. An example can be found here. Javascript (js):
function navbar() {
// create variables
var subNavTimer;
var open;
// to make sure that when user mouses over sub menu ul it stays open
$("ul.subNav").mouseover(function() {
 $(this).show();
 // lets remember what's open
 open = $(this).parent();
});
 
// when user mouses over main item in navbar
$("li.navMainLink").mouseover(function() {
 // close other nav item submenus
 if (open != null) open.children("ul").hide();
 // stop the timer
 clearTimeout(subNavTimer);
 // show this nav item's sub menu
 if ($(this) != open) $(this).children("ul:hidden").show();
 
});

// when user's mouse leaves the navbar item
$("li.navMainLink").mouseout(function() {
 // lets keep tabs of what is open
  open = $(this);
 // start the timer for 2 seconds until it closes.
  subNavTimer = setTimeout('open.children("ul:visible").hide();', 2000);
});
}

$(document).ready(function() {
 navbar();
});
HTML:
<ul id="navMain">
<li class="navMainLink">
  <a class="navLink" href="#">Performances</a>
  <ul class="subNav">
   <li>
    <a href="#">Season Subscriptions</a>
   </li>
   <li>
    <a href="#">About the Shows</a>
   </li>
  </ul>
 </li>
</ul>
CSS: Your decision! Make it a vertical drop down or make it a horizontal fly out. Just make sure to have the ul.subNav be display: none; by default in your CSS.

Labels: , ,

5 Comments:

Blogger Unknown said...

this line is wrong.
subNavTimer = setTimeout('open.children("ul:visible").hide();', 2000);

May 22, 2008 at 3:24 AM  
Blogger Alex Grande said...

What's "wrong" about it?

I am open to improvements to anything on The True Tribe. Please provide with examples or ways to make anything better. Although it works perfectly and the link at the top of this post proves that. Jonah Dempcy suggested this though:

subNavTimer = setTimeout(function() {
open.children("ul:visible").hide();
}, 2000);

As a way to increase performance.

May 29, 2008 at 3:28 PM  
Blogger Lowell Kirsh said...

I'd refrain from adding those vars to the global namespace if possible. One way to do so would be to wrap your code like so:

(function() {
{YOUR CODE GOES HERE}
})();

June 8, 2008 at 11:28 PM  
Blogger Ulisses José said...

Well, the iten navMain doesn't show when I focus mouse pointer on the link. I think I have use a CSS style for configuration. Do you understand me? Can you help me? Tanks

August 21, 2008 at 1:40 PM  
Blogger Alex Grande said...

If you are having trouble with the CSS I suggest double checking everything. I think you may have some coding specificity issues?

August 26, 2008 at 10:04 PM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home