'Bootstrap collapse all accordions on button click
Is there a way to collapse/expand all accordions with a button click? I tried it with a simple button that removeClass active and addClass active but it did not work at all. I can only open them all up at once but not collapse again and then open up again.
my current button :
$("#collapseAll").click( function() {
$(".accordion-header").removeClass("active").addClass("active");
});
my js:
$('.js-accordion dt, .js-toggle').on('click tap', function(){
$($(this).data('target') ? $(this).data('target') : $(this)).toggleClass('active');
});
and my html
<dl class="accordion js-accordion" data-toggle="accordion-header">
{{#each accordion}}
<div id="{{anchor}}-div">
<dt class="accordion-header{{#if active}} active{{/if}}">
<h3 class="accordion-item-title"{{#if anchor}} id="{{anchor}}"{{/if}}>{{{title}}}</h3>
<span class="accordion-item-icon"></span>
</dt>
<dd class="accordion-body">
<div class="accordion-item-content">
{{#if textblock}}
{{#each textblock}}
<p>{{{.}}}</p>
{{/each}}
{{/if}}
<p>{{#if anchor}}<a href="#{{anchor}}" class="faq-anchor">{{../../page-contents.section-main.texts.permalink}}</a>{{/if}}</p>
<p><a href="#top">{{../../page-contents.section-main.texts.to_top}}</a></p>
</div>
</dd>
</div>
{{/each}}
</dl>
Solution 1:[1]
I did it by myself with this code
$("#collapseAll").click( function() {
let button = document.getElementById("collapseAll");
if(!$('.accordion-header').hasClass("active")){
$('.accordion-header').removeClass("active").addClass("active");
button.innerHTML = 'Collapse all'
} else {
$('.accordion-header').addClass("active").removeClass("active");
button.innerHTML = 'Expand all'
}
});
also with changing button text!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | lorijames95 |