How To: Select a tab from a URL using jQuery

by Art Armstrong on April 9, 2009

The latest issue that I have run into and had to fix was trying to select a tab from the URL so that we had some dynamic control of what was shown when the page loaded. This was mainly a concern for a couple of pages where the page had to be reloaded or redirected to after a action was performed.

TheĀ tabs that jQuery has made available are some of the most useful and powerful tools that I have used within a new web application for a long time but as with anything there are a few things that aren’t built in which need to be remedied.

picture-1

The first thing we need to do is create the jQuery code and the HTML for the tabs, don’t forget to include the jQuery files

jQuery Tab Information

$(function(){

// Initialize Tabs
$('#my-tabs').tabs();

});

HTML tab code

<div id="my-tabs">
	<ul>
    		 <li><a href="#my-tabs-1"><span>One</span></a></li>
    		 <li><a href="#my-tabs-2"><span>Two</span></a></li>
    		 <li><a href="#my-tabs-3"><span>Three</span></a></li>
	</ul>
	<div id="my-tabs-1">
		<p>First tab is active by default</p>
	</div>
	<div id="my-tabs-2">
		<p>Second tab</p>
	</div>
	<div id="my-tabs-3">
		<p>Third tab</p>
	</div>
</div>

Now that we have the basics of the tabs set up you just have to add a little bit of code to check if a hash has been passed through the URL and then select that tab. The way that this would be called would be something like, although it wont work:

http://www.getrentwiz.com/test-tabs/index.html#2

So here is the code that will added below the tab initialization that will allow the tab to be selected.

$(function(){

// Initialize Tabs
$('#my-tabs').tabs();

if(document.location.hash!='') {
        //get the index from URL hash
      	tabSelect = document.location.hash.substr(1,document.location.hash.length);
	$("#my-tabs").tabs('select',tabSelect-1);
}

});

Now as you will see in the code that we subtract the number passed through the hash by 1, this is to accommodate the 0-based index that arrays use. So for example, passing 2 would return the select of 1, which is array[1], or the second tab. I hope this helps out a few people that ran into the same problem but I cant take all the credit, most of this was learned from Raymond Camden from O’Reilly InsideRIA and a few others.

Thanks for the interest!

{ 3 comments… read them below or add one }

Michael Willy 07.18.09 at 1:15 pm

Nicely done.
Thanks for the thinking this through and sharing.

emon 08.08.09 at 9:45 pm

Was looking for it. good job man!

Ivan Novak 01.29.10 at 7:28 pm

Art, absolutely wonderful. I’m working on a client project that requires exactly this fix. Why they would not build in this functionality is beyond me. Thanks a heap!
-Ivan

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>