I need to create a bootstrap accordion. The markup below works fine, but it does not auto-collapse the previously opened element. For example, open panel1, then click on panel2.. panel1 should then auto-close, but it does not. I have tried copying the markup exactly from the bootstrap site (http://twitter.github.com/bootstrap/javascript.html#collapse), but it is not working. What am I missing?
<h3>ACCORDION DEMO</h3>
<div class="accordion" id="accordion1">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-parent="accordion1" data-toggle="collapse" href="#panel1">Panel 1</a>
</div>
<div class="accordion-body collapse" id="panel1">
<div class="accordion-inner">
<p>This is accordion panel 1 content</p>
</div>
</div>
</div>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-parent="accordion1" data-toggle="collapse" href="#panel2">Panel 2</a>
</div>
<div class="accordion-body collapse" id="panel2">
<div class="accordion-inner">
<p>This is accordion panel 2 content</p>
</div>
</div>
</div>
</div>
Just add data-toggle="collapse" and a data-target to element, to automatically assign control of a collapsible element. The data-target attribute accepts a CSS selector to apply the collapse to. Be sure to add the class collapse to the collapsible element. If you'd like it to default open, add the additional class in .
This is done by getting all elements with class "accordion". By looping through these elements the panel div which holds the accordion description is used (next sibling element to the accordion element).
To create an accordion that is collapsed by default, we need to set the 'active' property of the jQuery Accordion as false.
In bootstrap context wise, accordion is basically a collapse button with a lot of smaller info in it. Bootstrap use card to make an accordion. on line 1, <div id="accordion" role="tablist"> , this is where the data-parent refers to. on line 2 <div class="card"> , we are using a card class, to show the card effect.
simply replace data-parent="accordion1"
with data-parent="#accordion1"
For posterity, another reason I just discovered that would prevent the accordion panels from auto-collapsing is if the .panel
elements are not direct children of the accordion (.panel-group
element). I had wrapped my panel content in a div
within my .panel-group
and the accordion didn't like that.
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