jQuery: dropdown menu and mouse events

Beside the actual building of a dropdown menu, the most difficult part of this kind of menus is controlling the mouse events to make sure that each submenu will be closed exactly when the user's mouse moves away from the content area of this menu. Dropdown menus are usually built using nested unordered lists. This poses a problem when dealing with mouse events because in this structure elements are nested so that their content areas overlap. For example, if you have a structure like this:

<li class="subnav"><a href="#">About</a>
      <li><a href="#">About us</a></li>
      <li><a href="#">Our projects</a></li>
      <li><a href="#">Details</a></li>
      <li><a href="#">Features</a></li>


When you hover the first link of the subnav list item the nested submenu is shown. So far so good. The problem here is that the content area of the list item, the link and the submenu itself overlap. With a situation like this, handling mouse events with jQuery can be difficult if you don't know what kind of events you should use. For the hover state there's no problem: the event is certainly mouseover:

$('#navigation li.subnav').each(function() {
    var $li = $(this);
    var $a = $li.find('a:first');
    var top = $a.position().top;
    var left = $a.position().left;
    $a.mouseover(function() {
        position: 'absolute', 
        top: top + 32, 
        left: left
    // code continues

Now you may be tempted to use the mouseout event (me too! smile) to make the submenu disappear. But, as you will soon notice, results are really frustrating because the submenu is hidden very quickly and, most of all, not at the right time. The solution is to use mouseleave instead:

// code continues

$a.next().mouseleave(function() {
  var menu = $(this);

With this event you get pretty good results. You can see a demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

One thought on “jQuery: dropdown menu and mouse events”

Leave a Reply

Note: Only a member of this blog may post a comment.