I'm working with JQuery Mobile and I have a bunch of accordions on my page. I want to expand/collapse all the accordions at once, at the click of a button. How can this be done?
Does something like this work?
JS
$('#openAll').on('click', function() {
$('.openMe').each(function() {
var coll = $(this);
coll.trigger('expand');
});
});
$('#closeAll').on('click', function() {
$('.openMe').each(function() {
var coll = $(this);
coll.trigger('collapse');
});
});
Alternate JS ( without the foreach ):
$('#openAll').on('click', function() {
$('.openMe').trigger('expand');
});
$('#closeAll').on('click', function() {
$('.openMe').trigger('collapse');
});
HTML
<div data-role="collapsible" class="openMe">
<h3>Hello 1</h3>
<p>I'm the collapsible content. By default I'm closed, but you can click the header to open me.</p>
</div>
<div data-role="collapsible" class="openMe">
<h3>Hello 2</h3>
<p>I'm the collapsible content. By default I'm closed, but you can click the header to open me.</p>
</div>
<div data-role="collapsible" class="openMe">
<h3>Hello 3</h3>
<p>I'm the collapsible content. By default I'm closed, but you can click the header to open me.</p>
</div>
<br />
<a href="#" data-role="button" id="openAll">Open All Collapsible</a>
<a href="#" data-role="button" id="closeAll">Close All Collapsible</a>
Docs:
Looks like this wont work on a set as only one can be open at a time:
Set Docs:
for some reason the above solution is not working for me ie; $('.openMe').trigger('collapse'); and $('.openMe').trigger('expand'); is not working.
So, I have rewritten the method slightly.
The Javascript code will look like this
$('#openAll').on('click', function() {
$(".ui-collapsible-heading").removeClass("ui-collapsible-heading-collapsed");
$(".ui-collapsible-content").removeClass("ui-collapsible-content-collapsed");
$(".ui-collapsible-heading a").addClass("ui-icon-minus").removeClass("ui-icon-plus");
});
$('#closeAll').on('click', function() {
$(".ui-collapsible-heading").addClass("ui-collapsible-heading-collapsed");
$(".ui-collapsible-content").addClass("ui-collapsible-content-collapsed");
$(".ui-collapsible-heading a").removeClass("ui-icon-minus").addClass("ui-icon-plus");
});
ie; adding and removing the required classes using jquery.
jsfiddle for the same
I stumbled across this post while trying to figure out why it wouldn't work on a collapsibleset which, as mentioned by Phil, isn't possible since only one can be open at a time.
It probably isn't the appropriate solution, but I was able to mimic the look of a collapsibleset while making it a simple collapsible by adding the following CSS to the collapsibles themselves:
.collapsible { margin: -1px 0 0; border-radius: 0; }
This then allowed me to open and close all of them using
$('.collapsible').collapsible('expand');
$('.collapsible').collapsible('collapse');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With