I'm trying to create an accordion using Bootstrap 3 using the button collapsible with the data attribute, without the accordion markup. It just looks more cleaner to me.
However I cannot make the data-parent attribute to work. I want when opening a question, all others to close. I'm reading the docs ( http://getbootstrap.com/javascript/#collapse-usage ) but still cannot get it to work.
I'm using the following code:
<div class="accordion" id="myAccordion">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
<div id="collapsible-1" class="collapse">
<p>Etiam posuere quam ac quam. Maecenas aliquet accumsan leo. Nullam dapibus fermentum ipsum. Etiam quis quam. Integer lacinia. Nulla est.</p>
</div>
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
<div id="collapsible-2" class="collapse">
<p>Etiam posuere quam ac quam. Maecenas aliquet accumsan leo. Nullam dapibus fermentum ipsum. Etiam quis quam. Integer lacinia. Nulla est.</p>
</div>
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
<div id="collapsible-3" class="collapse">
<p>Etiam posuere quam ac quam. Maecenas aliquet accumsan leo. Nullam dapibus fermentum ipsum. Etiam quis quam. Integer lacinia. Nulla est.</p>
</div>
</div>
Here is the JSFiddle: http://jsfiddle.net/twinsen/AEew4/
I'll be very happy if someone points to me where I'm making a mistake :\
Try this. Simple solution with no dependencies.
As Blazemonger said, #parent, .panel and .collapse have to be direct descendants. However, if You can't change Your html, You can do workaround using bootstrap events and methods with the following code:
If found this alteration to Krzysztof answer helped my issue
if you have nested panels then you may also need to specify which ones by adding another class name to distinguish between them and add this to the a selector in the above JavaScript
Note, not only there is dependency on .panel, it also has dependency on the DOM structure.
Make sure your elements are structured like this:
It's basically what @Blazemonger said, but I think the hierarchy of the target element matters too. I didn't finish trying every possibility out, but basically it should work if you follow this hierarchy.
FYI, I had more layers between the control div & content div and that didn't work.
Here is a (hopefully) universal patch I developed to fix this problem for BootStrap V3. No special requirements other than plugging in the script.
EDIT: Below is a simplified answer which still meets my needs, and I'm now using a delegated click handler:
I got the same problem when toggling the accordion. But when I try to put the script block in the header block, it works for my case!!