jQuery Accordion Open Automatically

Working with jQuery Accordions I ran into two issues that seemed to be simple but turned out to be a hassle since answers were all over the place from using Python to C++ to it can’t be done. So, after a lot of testing, I found a solution that worked for me for two jQuery accordion issues:

Automatically Have Accordion Open on a Page

I was designing a faculty page for work and really wanted it to open up to the first faculty member when someone arrived on the page. To accomplish this I took the standard jQuery for the accordion and added one additional line:
<script>
$( "#accordion" ).accordion({
heightStyle: "content",
active:false,
collapsible: true,
header:"div.accordionheader"
});
$("#accordion").accordion("option", "active", 0);
</script>

What this does is select the first accordion div to be opened on page load. Obviously, changing the 0 to a different number will edit what opens.

Assign IDs to automatically open an Accordion from an Outside Link

This was a bit more complicated to figure out but essentially what I wanted to do for work was to list out courses and upon clicking the link it navigated to an accordion style page that opened the correct corresponding accordion:

<script>
$( "#accordion" ).accordion({
heightStyle: "content",
active: false,
collapsible: true,
header:"div.accordionheader"
});
var hash = window.location.hash;
var anchor = $('a[href$="'+hash+'"]');
if (anchor.length > 0){
anchor.click();
}
</script>

Then also added to the accordion headers:

<div class="accordionheader">
<h4><a id="name" href="#name">Header Test</h4>
</div>

I found this trick via OpenStack and it got little recognition so I wanted to assert that it works.

(Image via sixrevisions.com)

Leave a Comment