Reputation: 3182
I'm trying to slideup and slidedown, submenus inside a menu. A submenu can also contain submenu and so on.
Here's the html:
<ul class="nav">
<li class="nav-parent"><a href="#">Level 1</a>
<ul class="nav-child">
<li class="nav-parent"><a href="#">Level 2</a>
<ul class="nav-child">
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
</ul>
</li>
<li><a href="#">some stuff</a></li>
<li><a href="#">some stuff</a></li>
<li><a href="#">some stuff</a></li>
</ul>
</li>
<li><a href="#">some stuff</a></li>
<li><a href="#">some stuff</a></li>
<li><a href="#">some stuff</a></li>
</ul>
As you can see there are two submenus, nested submenus*
$('.nav-parent').on('click', function(){
var me = $(this);
if(me.hasClass('child-opened')){
//child already opened > close
me.find("> .nav-child").slideUp(200);
me.removeClass('child-opened');
} else {
//child not opened > open
me.find("> .nav-child").slideDown(200);
me.addClass('child-opened');
}
});
The jQuery works for first level, but does not work on second level. nav-child default is set to display:none in css.
Upvotes: 1
Views: 98
Reputation: 3277
The problem is in bubbling of event.
There are tways to fix this:
event.stopPropagation()
, here is working example.Upvotes: 1
Reputation: 3133
Just add a return false;
at the end of your method: Demo
$('.nav-parent').on('click', function (event) {
var me = $(this);
if(me.hasClass('child-opened')){
//child already opened > close
me.find("> .nav-child").slideUp(200);
me.removeClass('child-opened');
} else {
//child not opened > open
me.find("> .nav-child").slideDown(200);
me.addClass('child-opened');
}
return false;
});
Without the return false, it creates a bubbling of the event and calls the event for each of the parents.
To prevent event bubbling from the children, I added this:
$('.nav-child').on('click', function (event) {
return false;
});
Upvotes: 2