Posts

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:

[crayon]

The camera settings

The acquisition settings.

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

[crayon]

[/crayon]
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.

 

HTML / Javascript – Setting hash without browser scrolling.

Q: I set a document’s hash using:

 
document.location.hash = '#my-hash';
 

But this always causes the browser to automatically scroll to the top of the region identified by the hash. How can I set the url’s hash without the page scrolling?

 

A: On newer browsers you can use the new HTML5 History API to silently set the hash by using history.replaceState(), for example:

 
history.replaceState(null, null, 'my-hash');
 

When you set the hash in this way, the page won’t scroll. To see which browsers currently support the history API, check here.