views:

368

answers:

3

I'm building a simple dropdown where I'd like to add a class to parent if UL exists:

HTML:

<ul id="menu">
  <li><a href="#">Parent 1</a></li>
  <li><a href="#">Parent 2</a>
    <ul>
      <li><a href="#">Sub 2.1</a></li>
      <li><a href="#">Sub 2.2</a></li>
    </ul>
  </li>
</ul>

So I'd like to:

  • hide all nested (ul#menu > li > ul) ul's initially
  • show/hide nested ul on hover
  • addClass "dropdown" to parents that have nested ul's

This isn't quite working, not sure why:

$(function () {
    $("ul#menu li").hover(function () {
        $(this).addClass("hover");
        $('ul:first', this).css('visibility', 'visible');
    },
    function () {
        $(this).removeClass("hover");
        $('ul:first', this).css('visibility', 'hidden');
    });
    $("ul#menu li ul li:has(ul)").find("a:first").addClass("dropdown");
});

Many thanks for your help!

A: 

This should do the trick (untested):

$('ul#menu > li > ul').each(function()
{
    var list = $(this);
    list.hide();
    list.parent().hover(list.hide, list.show);
    list.parent().parent().addClass('dropdown');
});
Will Vousden
You cannot hover over a hidden item.
Victor Nicollet
Good call; I guess the hover needs to be on the list item.
Will Vousden
+2  A: 
var ul = $('#menu');

if (ul.length) {
    ul.children('li').hover(function() {
        $(this).children('ul').show();
    }, function() {
        $(this).children('ul').hide();
    }).children('ul').hide().parent().addClass('dropdown');
}

Demo: http://jsbin.com/ofayu

BTW: you are closing the <li> tags incorrectly in your markup.

David
Perfect, thanks! :)
Nimbuz
+1  A: 

You wrote:

$("ul#menu li ul li:has(ul)")

Given your HTML structure, shouldn't this be:

$("ul#menu li:has(ul)")
Victor Nicollet