Friday, December 13, 2013

Activate Accordion Section By URL Hash

The jQuery UI tabs widget has the ability to activate specific tab sections based on the hash string. For example, a link on another page may point to tabs.html#tab2, and when that address is followed, the second tab is opened as expected. This is not the case, however, with the accordion widget. For one thing, there are no links in the accordion header markup. Just headers. When the accordion is the main organizational unit on the page, it would be handy to have this linking ability.

We can add this capability to the accordion widget be adding IDs to the accordion header elements, and some hashchange event handling. For example, inside the create event, we can attach attach this event handler.

$( window ).on( "hashchange", function( e ) {
            
    var headers = $this.accordion( "option", "header" ),
        header = $( location.hash ),
        index = $this.find( headers ).index( header );
            
    if ( index >= 0 ) {
        $this.accordion( "option", "active", index );    
    }
            
});

First, we setup the variables. The headers variable is a selector string, used to find all the accordion headers. The header variable is a jQuery object that looks up the accordion header based on the location.hash property. The reason we're creating a jQuery object is so that the index() function will work as expected. Next, we find the index we're looking for, and put it in the index variable.

The reason we need the index value is so that we can activate the expected accordion section. But first we have to make sure he have a valid index, and if so, we can set the active option of the accordion.