Reputation: 157
How can I activate a tab based on a hash tag (element ID) in the URL?
I know this question has been asked several times over the years, but the answers are no longer relevant for jQuery 1.10+.
Thanks.
Upvotes: 0
Views: 545
Reputation: 1829
There's two steps to accomplishing this - first, match up the hash tag (e.g. #SomeValue) to the element ID of the Tab you want active; then second, set said Tab as active.
var matchedTab = $('a[href="' + window.location.hash + '"]');
$('#tabs').tabs({active:$('#tabs a').index(matchedTab)});
The first line is creating a jQ object from the tab element whose href
attributes matches the hash in the URL. Since the markup of the Tabs plug-in requires (documentation) you have an anchor <a>
element with an href
attribute, this will find the correct tab (assuming you have one that corresponds to the hash in the URL).
The second line then uses the active
initialization option to set the desired active tab when initializing the Tabs. The active
option though requires the zero-based index of that tab within the Tabs collection, so we use the .index()
jQuery function to get that index & pass it to the active
option.
Since the sandbox sites all use secured frames, I had to use a dropdown with dummy URLs to "simulate" different how different hash tags work, but it will function just the same using the code above.
CodePen here: https://codepen.io/anon/pen/YvyxvL
You can use the dropdown on that page to simulate the behavior of URLs with different hash tags setting different tabs to active.
Upvotes: 1