I'm trying to create previous / next buttons on each accordion body.
I can't figure out a way to collapse / expand a certain section. I tried removing the class in
from the accordion-body
but that does not seem to collapse.
$(".accordion-body").each(function(){ if($(this).hasClass("in")) { $(this).removeClass("in"); } });
Also whenever or whatever I use the .collapse
method on, I get a javascript error saying that object has no method collapse.
To control (show/hide) the collapsible content, add the data-toggle="collapse" attribute to an <a> or a <button> element. Then add the data-target="#id" attribute to connect the button with the collapsible content (<div id="demo">).
By default, accordion items expand or collapse by clicking the accordion item header or clicking expand/collapse icon in accordion header. You can also expand or collapse the accordion items through external button click.
Assuming that you're using Bootstrap 4, you can simply remove the data-parent attribute from the element with the collapse class. This subscribes the collapse to events on #accordionExample , which is the main accordion element, via the data-parent attribute.
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');
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
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