Reputation: 3380
I have never used jQuery before and I'm trying to do something really simple but it's been driving me crazy.
I have designed a template for a CMS and now I want to get its menus animated.
The picture below explains the structure of the menu (which is obviously generated by the CMS)
The code below is what I think should work, but it doesn't:
var menuItem = jQuery(".menu:first>li");
var subMenu;
for(var i=0; i<menuItem.length;i++)
{
var li = jQuery(menuItem[i]);
subMenu = li.children("ul");
if (subMenu.length)
li.hover(function(){ li.children("ul").slideToggle(250); });
}
Basically, what I'm doing is get the first level li
s and then add a hover
listener to them, telling them to animate their child ul
(which is the actual sub menu).
What I get instead is when I point to "Products" it's own sub menu does not show, instead, the sub menu for "Contact Us" pops up! When I point to "Contact Us" its sub menu pops up like it is supposed to. Note: The brown ul
is set to display:none
I appreciate any help.
Thank in advance
PS: I'm using jQuery 1.7.1 (if it matters)
Upvotes: 2
Views: 666
Reputation: 66
I see what you're trying to do in your code but I think you should start with good jQuery practices first. It's really not hard, you'll see. And it will make your life a lot easier.
First of all, I'm not sure a loop is what you want here. jQuery offers a selector (which can be used with $ as a shortcut) to select classes and it's really powerful. Build your menu like this (sort of):
<ul id="menu">
<li class="menu-item">Home
<ul>
<li></li>
<li></li>
</ul>
</li>
<li class="menu-item">Products
<ul>
<li></li>
<li></li>
</ul>
</li>
<li class="menu-item">Contact us
<ul>
<li></li>
<li></li>
</ul>
</li>
</ul>
Then you can select the menu items with
$('.menu-item')
and in its hover function, select the drop down with
$(this).childen('ul')
Then basically have fun!
Upvotes: 1
Reputation: 11431
It looks quite complicated for what your trying to achieve. i would do something like this.
$(".menu > li").hover(
//When mouse is over the menu button
function () {
$(this).children("ul").slideDown(250);
},
//When mouse leaves the menu / menu button
function () {
$(this).children("ul").slideUp(250);
}
);
Upvotes: 2