Reputation: 17392
I've an unordered list.
<div class="categories-list">
<ul class="display_categories">
<li>
<a class="title"><span><b>1</b></span></a>
<ul class="display_subcategories">
<li><a>22</a></li>
<li><a>22</a></li>
</ul>
</li>
<li>
<a class="title"><span><b>1</b></span></a>
<ul class="display_subcategories">
<li><a>22</a></li>
<li><a>22</a></li>
</ul>
</li>
</ul>
</div>
I want that when a user clicks on any category, its sub-category should slidedown and whenever the same category is clicked, nothing should happen. Here's my jQuery
$('.display_subcategories').hide()
$('.title').click(function(){
$('.display_categories').children().children('ul').slideUp('fast');
$(this).next().slideDown('fast');
})
but what happens is that upon clicking on the already slideDown category, it again slides up and then slides down.
Here is the jsFiddle link
Upvotes: 2
Views: 233
Reputation: 2390
I would suggest letting CSS manage your animations by triggering or disabling classes. A simple example would be adding the .active
class to an open <ul>
, and the following CSS:
.display_subcategories { max-height: 0; overflow: hidden; transition: all 300ms; }
.display_subcategories.active { max-height: 50px; }
Here is a modified JSFiddle with my suggestion.
Upvotes: 0
Reputation: 1691
Try this
$('.display_subcategories').hide();
$('.title').click(function(){
if(!$(this).hasClass('down')){
$('.title').removeClass('down');
$('.display_categories').children().children('ul').slideUp('fast');
$(this).next().slideDown('fast');
$(this).addClass('down');
}
})
Upvotes: 0
Reputation: 337656
You can slideDown
the current submenu, then use not()
to slideUp()
all except the current, like this:
$('.display_subcategories').hide()
$('.title').click(function() {
var $submenu = $(this).next().slideDown('fast');
$('.display_categories').find('> li > ul').not($submenu).slideUp('fast');
});
Note also the use of find()
with the descendant selector over chained children()
calls.
Upvotes: 2