Looping through elements for drop down menu
I am trying to make my own jquery drop down menu. As usual, HTML is like this:
-
<ul class="menu">
<li class="parent item79"><a href="#"><span>Top Item 1</span></a>
<ul>
<li class="item101"><a href="#"><span>Sample sub-menu 1</span></a></li>
<li class="item102"><a href="#"><span>Sample sub-menu 2</span></a></li>
<li class="item103"><a href="#"><span>Sample sub-menu 3</span></a></li>
</ul>
</li>
<li class="parent item80"><a href="#"><span>Top Item 2</span></a>
<ul>
<li class="item101"><a href="#"><span>Sample sub-menu 1</span></a></li>
<li class="item102"><a href="#"><span>Sample sub-menu 2</span></a></li>
<li class="item103"><a href="#"><span>Sample sub-menu 3</span></a></li>
</ul>
</li>
</ul>
...and so on.
JS code that works in like this:
-
$('.menu > li:nth-child(1)').hover(function() {
$('.menu li:nth-child(1) ul li').animate({opacity: 'toggle'}, 'slow');
}, function() {
$('.menu li:nth-child(1) ul li').animate({opacity: 'toggle'}, 'slow');
}); // this is for drop down 1
$('.menu > li:nth-child(2)').hover(function() {
$('.menu li:nth-child(2) ul li').animate({opacity: 'toggle'}, 'slow');
}, function() {
$('.menu li:nth-child(2) ul li').animate({opacity: 'toggle'}, 'slow');
}); // this is for drop down 2
... and so on for each top level menu item.
When I use variable like this:
-
var index=1;
$('.menu > li:nth-child(' + index + ')').hover(function() {
$('.menu li:nth-child(' + index + ') ul li').animate({opacity: 'toggle'}, 'slow');
}, function() {
$('.menu li:nth-child(' + index + ') ul li').animate({opacity: 'toggle'}, 'slow');
});
...it does work. But when I try to make code shorter with for or while loop, like this:
-
while (index < 10) {
$('.menu > li:nth-child(' + index + ')').hover(function() {
$('.menu li:nth-child(' + index + ') ul li').animate({opacity: 'toggle'}, 'slow');
}, function() {
$('.menu li:nth-child(' + index + ') ul li').animate({opacity: 'toggle'}, 'slow');
});
index++;
}
...it doesn't work. Top menu shows, but drop down on hover doesn't show.
I am new in jquery. Please help.