1

I have a screen that uses jQuery tabs and was wondering if somehow I can keep the selected tab after a refresh of the page (JS .reload();)?

Any guidance appreciated.

connersz
  • 1,153
  • 3
  • 23
  • 64

2 Answers2

1

https://github.com/carhartl/jquery-cookie

or

http://code.google.com/p/cookies/downloads/detail?name=jquery.cookies.2.2.0.js.zip&can=2&q=

Example for jquery.cookies.2.2.0.js

$(document).ready(function () {
   var initialTabIndex = 0;
   var jCookies = jQuery.cookies;

   //alert('getting ' + jCookies.get("currentTab"));

   if(jCookies.get("currentTab") != null){
      initialTabIndex = jCookies.get("currentTab");
   }

   $('#tabs').tabs({
      activate : function(e, ui) {
         //alert('setting ' + ui.newTab.index());
         jCookies.set("currentTab", ui.newTab.index().toString());
      },
      active : initialTabIndex
   });
});
Sully
  • 14,672
  • 5
  • 54
  • 79
  • I tried this but get an error message: Error: Object doesn't support property or method 'cookie'. – connersz Jan 27 '14 at 09:58
  • I updated the code fixing some bugs. It is working now just make sure you add jquery.cookies.2.2.0.min.js – Sully Jan 27 '14 at 11:43
  • If you thought my question was valid, would you mind up voting it for me, thanks again. – connersz Feb 05 '14 at 12:55
0

While the previous answer using cookies will certainly work, it is probably not the ideal solution given peoples aversions to accepting cookies. (it also means you would need to show a disclaimer on your site stating you use cookies, at least to EU visitors). I'd recommend avoiding using cookies where possible so your site remains functional if cookies are disabled/rejected.

A better way is to use the "hash" on the end of a URL.

Modify your tab links as follows:

<div id="UITabs">
<ul>
    <li><a href="#Tab1">Tab 1</a></li>
    <li><a href="#Tab2">Tab 2</a></li>
    <li><a href="#Tab3">Tab 3</a></li>
</ul>
<div id="Tab1"></div>
<div id="Tab2"></div>
<div id="Tab3"></div>
</div>

Then in your head, add the following javascript to ensure the hash is set when changing tabs, and get the hash on pageload and display the required tab:

$(document).ready(function () {

    $(function () {
        $("#UITabs").tabs();

        $("#UITabs").bind("tabsshow", function (event, ui) {
            location.hash = ui.newTab.find('a.ui-tabs-anchor').attr('href');
        });

        $(window).bind('hashchange', function (e) {
            $("#UITabs").tabs("select", location.hash);
        });
    });
});
Gavin Coates
  • 1,366
  • 1
  • 20
  • 44