Reputation: 1244
i have a list order looking like these:
<ul>
<li>level 1 a
<ul>
<li>level 2 a
<ul>
<li>level 3 a</li>
<li>level 3 b</li>
</ul>
</li>
<li>level 2 b</li>
</ul>
</li>
<li>level 1 b
<ul>
<li>level 2 c
<ul>
<li>level 3 c</li>
<li>level 3 c</li>
</ul>
</li>
<li>level 2 d</li>
<li>level 2 e</li>
</ul>
</li>
</ul>
and jquery looking like these:
$(document).ready(function(){
$('li').click(function(ev) {
ev.stopPropagation();
$(this).children('ul').show();
$(this).prev().children('ul').hide();
$(this).siblings().children('ul li ul').hide();
$(this).next().children('ul').hide();
});
$('li > ul').hide();
});
current situation:
1) i click on level 1 a then level 2 a, now level 1 a and level 2 a are expanded
2) i click on level 1 b, then i click back the level 1 a, i still see the level 1 a and its child is expanded.
the outcome i want is:
when i click back level 1 a, it will collapse everything, instead of showing everything that i clicked before, same goes to level 1 b, if i click that 1st.
any help would be great. thanks
Upvotes: 1
Views: 520
Reputation: 12152
You can call hide on children ul
whenever a sibling
li
is clicked using this
$('li').click(function(ev) {
$(this).siblings('li').click(function() {
$(this).siblings('li').children('ul').hide()
})
$(document).ready(function() {
$('li').click(function(ev) {
$(this).siblings('li').click(function() {
$(this).siblings('li').children('ul').hide()
})
$(this).children('ul').children('li').children('ul').hide()
ev.stopPropagation();
$(this).parent('ul').show();
$(this).children('li').hide();
$(this).siblings('li').children('ul li ul').hide();
$(this).children('ul').show();
$(this).prev('li').children('ul li ul').hide();
$(this).next().children('ul').hide();
});
$('li > ul').hide();
});
current situation: 1) i click on level 1 a then level 2 a,
now level 1 a and level 2 a are expanded 2) i click on level 1 b,
then i click back the level 1 a,
i still see the level 1 a and its child is expanded. the outcome i want is: when i click back level 1 a,
it will collapse everything,
instead of showing everything that i clicked before,
same goes to level 1 b,
if i click that 1st.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>level 1 a
<ul>
<li>level 2 a
<ul>
<li>level 3 a</li>
<li>level 3 b</li>
</ul>
</li>
<li>level 2 b</li>
</ul>
</li>
<li>level 1 b
<ul>
<li>level 2 c
<ul>
<li>level 3 c</li>
<li>level 3 c</li>
</ul>
</li>
<li>level 2 d</li>
<li>level 2 e</li>
</ul>
</li>
</ul>
Upvotes: 1