Jquery UI Tabs - Extending Tab Behavior To Anchor Links

I was recently working with Jquery UI's tabs on a site. It does a fantastic job of making web standard reasonable markup into tabs. The whole thing is a simple enough overlay that any end user could make the needed tab structure themselves (with just a bit of copy paste). But, it turns out, Jquery UI Tabs do slightly less than I thought they did. It turns out the standard tabs call limits its behavior changes to only the div called in question. I suppose that makes perfect sense really, but it doesn't to end users. They see a link in the tabs list to "#tab," and think they should be able to duplicate the effect within their content, for massive cross tab linking potential. And you know, that does make sense too. Why shouldn't a link (anchor) to a shortcut (hash) that is in fact, a tab on the page, open that tab? It's not like you're going to run across another div with that same id they are meaning to shortcut to. And so, I give you this:

  1. // This is the standard Jquery UI Tabs initial call
  2. $('.tabs').tabs();
  4. /*Custom Fragment to check all the anchors on the page, and change the behavior of any that link to a tab, to open it.
  5.  *Note that this skips the actual tabs on a page, so their behavior is not affected */
  6. $('a[href]').each(function(){
  7.         if(this.hash){
  8.                 if($(this.hash + '.ui-tabs-panel').length > 0 && $(this).parents('div.ui-tabs').length == 0 ){
  9.                         link = this.href.replace(this.hash, '');
  10.                         page = window.location.href.replace(window.location.hash, '');
  11.                         if(link == page || link == ''){
  12.                                 this.onclick = function(){
  13.                                         $('.tabs').tabs('select', this.hash);
  14.                                         return false;
  15.                                 }
  16.                         }
  17.                 }
  18.         }
  19. });

This code will open a tab from a link in any of the following formats:

It will not interfere with links leading to other pages.


Discovered a slight bug in this that disabled all anchor links. Updated code is in the main copy now.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.