bootstrap.js Accordion Collapse / Expand
Here is another solution:
/**
* Make an accordion active
* @param {String} id ID of the accordion
*/
var activateAccordion = function (id) {
// Get the parents
var parents = $('a[href="#' + id + '"]').parents('.panel-group').children('.panel');
// Go through each of the parents
$.each(parents, function (idx, obj) {
// Check if the child exists
var find = $(obj).find('a[href="#' + id + '"]'),
children = $(obj).children('.panel-collapse');
if (find.length > 0) {
// Show the selected child
children.removeClass('collapse');
children.addClass('in');
} else {
// Hide the others
children.removeClass('in');
children.addClass('collapse');
}
});
};
The important part of the code is the combination, remembering the .collapse class, not just using .in:
// Show the selected child
children.removeClass('collapse');
children.addClass('in');
and
// Hide the others
children.removeClass('in');
children.addClass('collapse');
The above example has been tested in Twitter's Bootstrap v3.3.4
The in
class is just an indicator that a section is open. The Javascript module applies the same inline styles as .in
does, so removing the class is insufficient.
You need to use the module's API to programmatically interact with the accordion, via the .collapse()
method:
$('.accordion-body').each(function(){
if ($(this).hasClass('in')) {
$(this).collapse('toggle');
}
});
Or, you can condense this down to:
$('.accordion-body.in').collapse('toggle');
If you want only to collapse any open sections:
$('.accordion-body').collapse('hide');
If you want only to expanded any closed sections:
$('.accordion-body').collapse('show');
This works for accordions in Bootstrap 3:
var selector = $('.panel-heading a[data-toggle="collapse"]');
selector.on('click',function() {
var self = this;
if ($(this).hasClass('collapsed')) {
$.each(selector, function(key, value) {
if (!$(value).hasClass('collapsed') && value != self) {
$(value).trigger('click');
}
});
}
});
I'm simulating a click of the other accordion tabs with $(value).trigger('click');
. According to the API you should just be able to use the .collapse()
method i.e. $(value).collapse('hide');
. But it doesn't work for some reason so trigger
it is...