I have multiple jquery accordions on one page all with different id\'s etc.. I\'m attempting to only allow one accordion to open at a time. For example the user opens one an
Assuming you are using the jQuery UI accordion, you can collapse all sections with .accordion('activate', false)
.
First, in your HTML, give all accordion containers class="accordion"
to make them more readily addressable as a group. You can keep the id="accordion1"
etc. attributes if you need to address the accordions individually.
Then, initialize the accordions in a single $(function(){...})
structure (just once, not 3 times), as follows :
$(function() {
var activeAccordian = null;
var $accordions = $(".accordion").on('click', function() {
activeAccordian = this;
}).accordion({
collapsible: true,
active: false,
icons: false
}).on('accordionchange', function(event, ui) {
$accordions.not(activeAccordian).accordion('activate', false);
});
});
DEMO
Tracking the active accordion with activeAccordian
is all important as it allows reciprocal re-closure of the freshly opened accordion to be suppressed.
The "aussi la solution" below, in which .on('accordionchange' ...)
is replaced with .on('click' ...)
makes me realise that the whole thing will simplify to :
$(function() {
var $accordions = $(".accordion").accordion({
collapsible: true,
active: false,
icons: false
}).on('click', function() {
$accordions.not(this).accordion('activate', false);
});
});
The need to track the active accordion disappears as .not(this)
in the click handler suffices.
DEMO