views:

89

answers:

1

I'm trying to make a navigation dropdown with jQuery that looks like this:

<ul id="home" >
    <li class="navtab"><a href="#">TABANME</a></li>
    <li class="homesub"><a href="#">Some link</a></li>
    <li class="homesub"><a href="#">Some link</a></li>
    <li class="homesub"><a href="#">Some link</a></li>
</ul>

The <li> .navtab is visible at all times - the submenu items start out hidden. I've attached the .hover() to the <ul> element (#home), but when the cursor enters the submenu <li> elements, the mouseout for #home fires, and the submenu items hide.

I know this has to do with event bubbling and mouseover/mouseout, but I can't figure out the logic of how to keep the menu open while the cursor is over the entire <ul>. The jQuery I currently have is:

    $('#thome').hover(
        function(){
           tabShowSubnav($(this).attr('id'))
        },
        function(){
           tabHideSubnav($(this).attr('id'))
        });

function tabShowSubnav(menu){

var tb = '#' + menu;
var sb = '.' + menu.slice(1) + 'sub';

$(tb).css('height','239px');
$(sb).show();
}

Any suggestions?

+4  A: 

Do yourself a huge favour and change how you structure your menu markup to:

<ul id="home" >
  <li class="navtab">
    <a href="#">TABANME</a>
    <ul class="submenu">
      <li><a href="#">Some link</a></li>
      <li><a href="#">Some link</a></li>
      <li><a href="#">Some link</a></li>
    </ul>
  </li>
</ul>

And put the hover event on li.navtab to make the submenu visible. You'll find this much easier to do. For example, the CSS:

ul.submenu { display: none; }

with:

$(function() {
  $("li.navtab").hover(function() {
    $(this).children("ul.submenu").show();
  }, function() {
    $(this).children("ul.submenu").hide();
  });
});

and you're most of the way there.

That all being said, I'd highly suggest using an existing jQuery menu plugin. There are lots of these about. I've had relatively good experience with superfish. There's little point reinventing this particular wheel.

cletus
+1 for Superfish. It's a great way to build these kinds of menus really easily.
S Pangborn
+1 Awesome answer, cletus.
roosteronacid