tags:

views:

32

answers:

2

I'm new to jQuery, so please bear with me. I'm trying to make my submenu appear on hover. The second set of <ul> is for submenu.

$(document).ready(function(){
    $('ul.menu.li').hover(
        function() { $('ul', this).css('display', 'block'); },
        function() { $('ul', this).css('display', 'none'); });
});

<ul id="menu">
<li><a href="#">Item 1</a><li>
<ul>
<li>Hi</li>
</ul>
<li><a href="#">Item 2</a></li>
</ul>
+1  A: 

Your selector is wrong. You need to reference the parent UL by ID, not class:

$('#menu li').hover(...

moreover, if you are addressing LIs within the UL, you want to use either ancestor-descendant or parent > child:

$('#menu li') // ancestor descendant
$('#menu > li') // parent > child

Additionally, there is no point in setting the CSS display property, when you can just:

$(document).ready(function(){
    $('#menu li').hover(
        function() { $('ul', this).show(); },
        function() { $('ul', this).hide(); });
});
karim79
<3 Are there any tips and suggestions for me too?
Doug
The `function() { $(this).show() }, function() { $(this).hide() });` isn't working. It's not selecting the second `<ul>`. It's just showing and hiding #menu li
Doug
@Doug - sorry, fixed it in the answer.
karim79
+1  A: 

There's a few things here, first the selector should be ul#menu li since menu is the id not the class (class selectors use .class). Also a space in there, otherwise it's looking for a <ul> with a class="menu li" to match.

Then, your <ul> needs to be a child of the <li> not a sibling, like this:

<ul id="menu">
<li><a href="#">Item 1</a>
    <ul>
    <li>Hi</li>
    </ul>
</li>
<li><a href="#">Item 2</a></li>
</ul>​

Lastly, you can add a bit of flair as well, like this:

$('ul#menu li').hover(function() { 
    $('ul', this).slideDown(); 
}, function() {
    $('ul', this).slideUp(); 
});​

This creates a sliding effect as well that you can see here

Nick Craver
It's so much cleaner if it were to be a sibling. Should I change my jQuery to accommodate that?
Doug
@Doug - Nope, it's invalid HTML if you try, and the results won't be predictable once you break the rules :)
Nick Craver
@Nick - `ul#menu` is actually marginally slower than just `#menu`. (fun nitpick :)
karim79
@karim - But if you have `div#menu` on another page... :) I tend not to change that, since I've seen users with that case more than a few times, even if I do think they're nuts ;)
Nick Craver
I see. Now I'm testing with divs, and don't understand why is it failing. Let me update my question
Doug
nevermind, the divs work!
Doug