Fix jQuery UI Tabs to Update Browser Location


When I spoke at MinneWebCon 2009 about Standardizing Web User Interfaces I covered one of my major pet peeves on the web: when content that can and should have a direct link, does not.

(The most common example would be the all-Flash portfolios and galleries of designers. You get three pages into their sites looking at a particular piece of their work, and then you look up in your browser location bar and you are still at ... I can't share their design work with somebody even if I wanted to, because there is no link! Terrible SEO and self-promotion.</rant>)

In terms of web user interface widgets, the very common tab view is often done incorrectly. For instance, both YUI's tab view and jQuery UI's tab view fail to change the browser's location when you switch tabs.

You can already directly link to a tab if you know the URL or right-click the tab to find the URL. However, if I use my browser's default bookmarking behavior, or if I use the location bar to copy and paste a link to somebody, or any number of other scenarios — because neither the YUI nor jQuery's tab views update the browsers location when you switch tabs, you are likely to send somebody a link to the first tab you landed on rather than the tab you are viewing.

The strangest part of all this is that enabling the direct linking on the back end is actually the hard part. Getting the location to update as you switch tabs is laughably easy. Here is the code for the default jQuery tab view behavior:

To fix the jQuery tab view so that it updates the browsers location as you switch tabs, the code looks like this:

$('#tabs ul li a').click(function () {location.hash = $(this).attr('href');});

Couldn't be simpler. I've set it up so you can see it in action. In this fixed jQuery tabs example as you click the tabs you will see your browser's location update.

I have submitted a ticket.