Charles Tang Charles Tang - 5 months ago 14
Javascript Question

Multi Nested Expand and collapse

I am trying to create a nested expandable and collapse tab.
I am able to implement the first level. i.e. If I click on key1, it will expand the list.

However, for key 5, when I click on it, both the second level and third level expand. Is there a way that when I click on key 5, only the second level will expand.

Is there any better way to create a nested expand and collapsable data?

https://jsfiddle.net/charles30hk/8ykLdnox/

HTML Code:

<ul class="archive_0">
<li class="level_0">key1
<ul class="archive_1">
<li class="level_1">key11 value11</li>
<li class="level_1">key12 value12</li>
</ul></li><li class="level_0">key2 value2</li>
<li class="level_0">key3 value3</li>
<li class="level_0">key4 value3</li>
<li class="level_0">key5
<ul class="archive_1">
<li class="level_1">key51 value11</li>
<li class="level_1">key52 value12</li>
<li class="level_1">key53<ul class="archive_2">
<li class="level_2">key531 value</li>
<li class="level_2">key52 value12</li>
</ul>
</li>
</ul>
</li>
</ul>


JS:

$('.archive_0 ul').hide();

$('.level_0').click(function() {
//$(this).parent().find('ul').slideToggle();
$(this).find('ul').slideToggle();
});


$('.archive_1 ul').hide();

$('.level_1').click(function() {
$(this).find('ul').slideToggle();
});

$('.archive_2 ul').hide();

$('.level_2').click(function() {
$(this).find('ul').slideToggle();
});

$('.archive_3 ul').hide();

$('.level_3').click(function() {
$(this).find('ul').slideToggle();
});

Answer

Your problem is that your level_1 function is finding all children ul and expanding them all, change your selector to get only the first level of children:

$('.level_0').click(function() {
    $(this).find(' > ul').slideToggle();
});

When you click on children elements, you will also need to stop the click event propagating to the parent too (as the child is within the parent, clicking on a child clicks the parent too). To stop the propagation do:

$('.level_1').click(function(ev) {
    ev.stopPropagation();
    $(this).find('ul').slideToggle();
});
Comments