I am learning how to use bootstrap to make an Expand/Collapse button. I have two items that can Expand/Collapse when clicked on and I also have a main Expand/Collapse for all items. The issue is when one item is expanded, and the other is not. The main Expand/Collapse button will close the first one but open the second one. How can I make the main button to Expand/Collapse whether the items are Expanded or not?
<div class="container">
<button type="button" class="btn btn-primary">Expand/Collapse</button>
<div class="card">
<div class="card-body">
<button class="card-title" data-toggle="collapse" data-target="#collapse" aria-expanded="false" aria-controls="collapse">Test</button>
<div class="card-text" id="collapse">
test
</div>
<button class="card-title" data-toggle="collapse" data-target="#collapse1" aria-expanded="false" aria-controls="collapse">
<strong>Test2</strong>
</button>
<div class="card-text" id="collapse1">
Beta2
</div>
</div>
</div>
below is the code for the main button:
$(".btn-primary").click(function(){
$(".card-text").collapse('toggle');
});
This was answered for Bootstrap 3.x here, and the concept is still the same, the individual collapse elements have there own Expand/Collapse state, and all the button is doing right now is toggling the state of each button.
The expand/collapse all button must track the current state of "Expand" or "Collapse" ALL.
$(".btn-primary").click(function(){
if ($(this).data("closedAll")) {
$(".collapse").collapse("show");
}
else {
$(".collapse").collapse("hide");
}
// toggle state and remember it
$(this).data("closedAll",!$(this).data("closedAll"));
});
// init with all closed
$(".btn-primary").data("closedAll",true);