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:

Then, as an example, to automatically open the second accordion section (identified by ‘#category-2’) when the page loads you could do the following:

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.

 
2 replies
  1. nabaraj devkota
    nabaraj devkota says:

    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

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *