Maintain active tab through multiple page loads

Maintain active tab through multiple page loads

I have a list of links:

  1. <ul class="links">
  2.     <li><a href="link-1.html">Page 1</a></li>
  3.     <li><a href="link-2.html">Page 2</a></li>
  4.     <li><a href="link-3.html">Page 3</a></li>
  5. </ul>

And below that some jQuery tabs:

  1. <div id="tabs">
  2.     <ul>
  3.         <li><a href="#tabs-1">First</a></li>
  4.         <li><a href="#tabs-2">Second</a></li>
  5.         <li><a href="#tabs-3">Third</a></li>
  6.     </ul>
  7.     <div id="tabs-1">First tab content</div>
  8.     <div id="tabs-2">Second tab content</div>
  9.     <div id="tabs-3">Third tab content</div>
  10. </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:

  1. <ul class="links">
  2.     <li><a href="link-1.html#tabs-2">Page 1</a></li>
  3.     <li><a href="link-2.html#tabs-2">Page 2</a></li>
  4.     <li><a href="link-3.html#tabs-2">Page 3</a></li>
  5. </ul>

Then, when clicking on any of the appended links, the active tab is opened on the new page as well.  But currently the active tab is only carried over to the next page. When linking to other pages after that (making no change to the active tab), it reverts back to the first tab. Is there a way to keep the active tab consistent through multiple page loads?

Here's the JS:

  1. $(function () {
  2.   var hashTab = window.location.hash;
  3.   var activeTab = 0;
  4.   if (hashTab.length > 0) {
  5.     activeTab = $('a[href^="#tabs-"]').index($('a[href="' + hashTab + '"]'));
  6.   }
  7.   $( "#tabs" ).tabs({
  8.     active: activeTab,
  9.     create: function(event, ui) {
  10.       $("ul.links a").attr('href', function(index, attr) {
  11.         this.href = attr.substr(0, attr.indexOf('#') == -1 ? attr.length : attr.indexOf('#')) + ui.tab.children().attr('href');
  12.       });
  13.     },
  14.     activate: function(event, ui) {
  15.       $("ul.links a").attr('href', function(index, attr) {
  16.         this.href = attr.substr(0, attr.indexOf('#') == -1 ? attr.length : attr.indexOf('#')) + ui.newTab.children().attr('href');
  17.       });
  18.     }
  19.   });
  20. });

Thanks in advance for any guidance!