PythonEnthusiast PythonEnthusiast - 7 months ago 108
Javascript Question

jQuery SlideDown only if another `ul` is clicked

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

Answer

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');
});

Updated fiddle

Note also the use of find() with the descendant selector over chained children() calls.