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):
// 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);
});
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: , ,