Fragmented Thought

jQuery UI Tabs - Extending Tab Behavior To Anchor Links

By

Published

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

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:

// This is the standard jQuery UI Tabs initial call $(".tabs").tabs(); /*Custom Fragment to check all the anchors on the page, and change the behavior of any that link to a tab, to open it. *Note that this skips the actual tabs on a page, so their behavior is not affected */ $("a[href]").each(function () { if (this.hash) { if ( $(this.hash + ".ui-tabs-panel").length > 0 && $(this).parents("div.ui-tabs").length == 0 ) { link = this.href.replace(this.hash, ""); page = window.location.href.replace(window.location.hash, ""); if (link == page || link == "") { this.onclick = function () { $(".tabs").tabs("select", this.hash); return false; }; } } } });

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

  • href="#tab"
  • href="/url/to/page#tab"

It will not interfere with links leading to other pages.