I’m trying to make a simple horizontal navigation bar with multiple levels (but for now, I’ve only made a navigation bar with one sublevel). I’m following this tutorial here with some modifications:
<ul id = "sample2">
<li>
<a href="#">About Us</a>
<ul>
<li><a href="#">Website</a></li>
<li><a href="#">Creator</a></li>
</ul>
</li>
<li>
<a href="#">Our Products</a>
<ul>
<li><a href="#">Product 1</a></li>
<li><a href="#">Product 2</a></li>
<li><a href="#">Just give us money</a></li>
</ul>
</li>
<li>
<a href="#">FAQs</a>
<ul>
<li><a href="#">What is this?</a></li>
<li><a href="#">Why should I care???</a></li>
</ul>
</li>
<li>
<a href="#">Contact</a>
<ul>
<li><a href="#">Telephone</a></li>
<li><a href="#">Mobile Phone</a></li>
<li><a href="#">E-mail</a></li>
</ul>
</li>
<li><a href="#">Login</a></li>
</ul>
I used only one id on the main <ul> and I’m accessing the sublevels using #sample2 ul instead of using classes on those.
However, it simply doesn’t work when I use the JQuery codes:
$(function () {
$('#sample2 ul').each(function () {
$(this).parent().eq(0).hover(function () {
$('#sample2 ul:eq(0)', this).show(100);
}, function () {
$('#sample2 ul:eq(0)', this).hide(100);
});
});
});
Again, I only changed the tutorial’s .dropdown class to #sample2 ul.
But it does work if I do the same way as the tutorial (i.e. assign either an id or a class on the sublevels), although I think it’s unnecessary since those sub-<ul>-s can be selected using css selectors.
What am I doing wrong? Are those sublevels really can only be selected using assigned classes/id on them?
This should do the trick. jsFiddle
EDIT:
It seems like you have some confusion about jQuery and how to use selectors (particularly selectors with context e.g.
$(selector, context)).In your example,
$('#sample2 ul')will select everyulthat is a descendant of #sample 2. If you wanted to add the same hover effect to eachul,$('#sample2 ul').hover(handler)or$('#sample2 ul').on('hover', handler)will do that for you. The problem is, you can’t hover over hidden items. So what you really want is to select theliunder #sample2 and attach your handler to their hover event.Within your hover event handler, you use the selector
$('#sample2 ul:eq(0)', this). The ‘this’ in that selector provides the context within which the#sample2 ul:eq(0)will be looked for. In an event handler,thisrefers to the element tied to that event. In this case, the hovered-overli. Eq(0) has no place inside the quotes of the selector, and as a general rule, should be avoided as part of any jQuery selector. Because there is no#sample2element within the context ofthisand because the:eq(0)malforms the selector,$('#sample2 ul:eq(0)', this)will return an empty jQuery object (nothing selected). What you wanted in your handler was$(this).children('ul'). Which will get theulthat is a direct child of the li currently hovered over.