Maintain active tab through multiple page loads
I have a list of links:
- <ul class="links">
- <li><a href="link-1.html">Page 1</a></li>
- <li><a href="link-2.html">Page 2</a></li>
- <li><a href="link-3.html">Page 3</a></li>
- </ul>
And below that some jQuery tabs:
- <div id="tabs">
- <ul>
- <li><a href="#tabs-1">First</a></li>
- <li><a href="#tabs-2">Second</a></li>
- <li><a href="#tabs-3">Third</a></li>
- </ul>
- <div id="tabs-1">First tab content</div>
- <div id="tabs-2">Second tab content</div>
- <div id="tabs-3">Third tab content</div>
- </div>
When clicking on a tab, the ID of the active tab is appended to all of the href attributes in the list of links. For example, when the second tab is active, the list of links looks like this:
- <ul class="links">
- <li><a href="link-1.html#tabs-2">Page 1</a></li>
- <li><a href="link-2.html#tabs-2">Page 2</a></li>
- <li><a href="link-3.html#tabs-2">Page 3</a></li>
- </ul>
Then, when clicking on any of the appended links, the active tab is opened on the new page as well.
Here's the JS:
- $(function () {
- var hashTab = window.location.hash;
- var activeTab = 0;
- if (hashTab.length > 0) {
- activeTab = $('a[href^="#tabs-"]').index($('a[href="' + hashTab + '"]'));
- }
- $( "#tabs" ).tabs({
- active: activeTab,
- create: function(event, ui) {
- $("ul.links a").attr('href', function(index, attr) {
- this.href = attr.substr(0, attr.indexOf('#') == -1 ? attr.length : attr.indexOf('#')) + ui.tab.children().attr('href');
- });
- },
- activate: function(event, ui) {
- $("ul.links a").attr('href', function(index, attr) {
- this.href = attr.substr(0, attr.indexOf('#') == -1 ? attr.length : attr.indexOf('#')) + ui.newTab.children().attr('href');
- });
- }
- });
- });
Thanks in advance for any guidance!