Your CSS has an error in :active
, where it should be .active
. And to open the other items with .toggle
you can use .siblings()
(brother elements).
It’s interesting to still use .preventDefault()
to cancel the link click event.
$(document).ready(function(){
$('.list-widget .list-group-item.active').click(function(e){
e.preventDefault();
$(this).siblings().toggle(400);
});
});
.list-widget .list-group-item { display: none; }
.list-widget .list-group-item.active { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<div class="list-group list-widget">
<a href="#" class="list-group-item active">Lista#01</a>
<a href="#" class="list-group-item">Item#01</a>
<a href="#" class="list-group-item">Item#02</a>
<a href="#" class="list-group-item">Item#03</a>
</div>
<div class="list-group list-widget">
<a href="#" class="list-group-item active">Lista#02</a>
<a href="#" class="list-group-item">Item#01</a>
<a href="#" class="list-group-item">Item#02</a>
<a href="#" class="list-group-item">Item#03</a>
</div>
To have the effect like "accordion", the .toogle()
must have a value, be it
numerical in milliseconds or "slow"
or "fast"
. In the above case I used 400
, an intermediate value between the "slow"
(600
) and slower than the "fast"
(200
).
Using . slideToggle()
The effect is much better using .slideToggle()
. That’s because the .toggle()
, during animation, increase (when showing) and reduce (when hiding) the width of the elements.
See the difference with .slideToggle()
:
$(document).ready(function(){
$('.list-widget .list-group-item.active').click(function(e){
e.preventDefault();
$(this).siblings().slideToggle(400);
});
});
.list-widget .list-group-item{ display: none; }
.list-widget .list-group-item.active { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<div class="list-group list-widget">
<a href="#" class="list-group-item active">Lista#01</a>
<a href="#" class="list-group-item">Item#01</a>
<a href="#" class="list-group-item">Item#02</a>
<a href="#" class="list-group-item">Item#03</a>
</div>
<div class="list-group list-widget">
<a href="#" class="list-group-item active">Lista#02</a>
<a href="#" class="list-group-item">Item#01</a>
<a href="#" class="list-group-item">Item#02</a>
<a href="#" class="list-group-item">Item#03</a>
</div>
Thank you Wictor!
– ElvisP