Twitter Bootstrap programmatically open or close an Accordion with javascript
Q: I have a nice accordion in my web app set-up in twitter bootstrap but how can I programmatically open or close a section using javascript?
A: Use the .collapse() function to open, close or toggle a collapsible accordion section.
Consider this 2 section accordion:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <div class="accordion" id="accordion2"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#category-1"><br /><br /> Camera Settings<br /><br /> </a> </div> <div id="category-1" class="accordion-body collapse" style="height: 0px; "> <div class="accordion-inner"> <p>The camera settings</p> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#category-2"><br /><br /> Acquisition Settings<br /><br /> </a> </div> <div id="category-2" class="accordion-body collapse"> <div class="accordion-inner"> <p>The acquisition settings.</p> </div> </div> </div> </div> |
Then, as an example, to automatically open the second accordion section (identified by ‘#category-2’) when the page loads you could do the following:
1 2 3 4 5 | <script> $(document).ready(function() { $('#category-2').collapse('show'); }); </script> |
This technique can be used to automatically re-open a previously open accordion section on page refresh, to do this first use the history api to update the current page location whenever a user clicks to open an accordion section – store an id to the open section in the page arguments.
Then when the page loads, for example on a refresh, if this argument exists parse it from the page loaction and then call collapse(‘show’) to open the section…
More details on .collapse() can be found here.
How can i make the first panel open by default. if i add the class .in to <div id="collapse” class=”panel-collapse collapse in”> and it opens them all by default instead of the first one. Any tips? Cheers Kevin
Try this: