Linking to JQuery UI accordion headers

I noticed recently that a number of people have tried to link to the headers of the JQuery UI accordion widget from a link on an external page so that when the page containing the widget loads, the selected menu is expanded. Quite a few of these people have found a solution that suited their needs. The aim of this post is to aid anyone who might still require a solution to this issue.

The solution that I like requires two lines of code. Before we get to the Javascript code, ensure that when you form your link to the page that you pass 0-based index of integers at the end of the URL. Examples of this are www.example.com/mypage.html#0 or www.example.com/mypost#0. The reason for this is because the ‘active’ option uses a 0-based index when referring to each header.

The first line of code will be used to grab the value that is passed with the URL and storing it to a variable. The purpose of the portion substring(1) is to ensure you only grab the value and not the ‘#’ symbol.

var x = location.hash.substring(1);

Next just include the variable as the value of the ‘active’ option while casting it as a number. The reason for casting the value as a number is because Javascript often stores values to variables as type String by default which the ‘active’ option would not recognise.

$( ".selector" ).accordion({ active: Number(x) });

or

$( ".selector" ).accordion( "option", "active", Number(x) );

I hope this post helps you to save you time as you try to get the most out of the JQuery UI accordion widget.

If you have any questions or comments, please feel free to add them below or contact me directly.

Leave a Reply

This entry was posted on Wednesday, July 6th, 2016 at 10:07 am and is filed under Development, JavaScript, JQuery. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.