18

I apologize for this being an open ended question, but I am at a loss.

Since version 1.9 of the jquery UI, they depreciated using the cookie option in order to save the active state of tabs across multiple pages. http://jqueryui.com/upgrade-guide/1.9/#deprecated-cookie-option

I haven't seen ANY other documentation out there on how to accomplish this now! So I am left scratching my head.

My best guess would be to use some sort of event to create a cookie, then load the cookie? Or is there some OTHER way to save the active state of the tabs across multiple pages and by user preference?

Alex Kulinkovich
  • 4,408
  • 15
  • 46
  • 50
PaulHanak
  • 729
  • 2
  • 9
  • 21

6 Answers6

19

Had the same issue bite me today. Here is what seems to work:

  1. Use jquery.cookie plugin (https://github.com/carhartl/jquery-cookie) (This step is not necessary, but it makes the life easier dealing with cookies)
  2. Use the following code fragment:

    $( ".selector" ).tabs({
        active   : $.cookie('activetab'),
        activate : function( event, ui ){
            $.cookie( 'activetab', ui.newTab.index(),{
                expires : 10
            });
        }
    });
    

This sets a cookie called "activetab" which expires after 10 days (refer to jquery.cookie documentation for more options) to remember the currently selected tab whenever any tab is clicked. This cookie is read at the initialization time to display the last saved tab. The first time the page is visited, the tabs will be collapsed.

journeyer
  • 800
  • 1
  • 7
  • 17
  • The jquery.cookie plugin was moved to [js-cookie](https://github.com/js-cookie/js-cookie). The code will change to: `$( ".selector" ).tabs({ active : Cookies.get('activetab'), activate : function( event, ui ){ Cookies.set( 'activetab', ui.newTab.index(),{ expires : 10 }); } });` – zipate Dec 24 '17 at 13:35
10

Short, layout-independent way of doing this using localStorage:

$("#tabs").tabs({
  active: localStorage.getItem("currentIdx"),
  activate: function(event, ui) {
      localStorage.setItem("currentIdx", $(this).tabs('option', 'active'));
  }
});

A layout-specific way of doing it using custom data attributes (possibly useful if the attribute values were to be used in some way elsewhere in your script).

jQuery UI:

$("#tabs").tabs({
    active: localStorage.getItem("currentTabIndex"),
    activate: function(event, ui) {
        localStorage.setItem("currentTabIndex", ui.newPanel[0].dataset["tabIndex"]);
    }
});

Example HTML layout:

<div id="tabs">
    <div id="tabs-1" data-tab-index="0">
       tab 1 stuff...
    </div>
    <div id="tabs-2" data-tab-index="1">
       tab 2 stuff...
    </div>    
    <div id="tabs-3" data-tab-index="2">
       tab 3 stuff...
    </div>
</div>
dsgriffin
  • 66,495
  • 17
  • 137
  • 137
6

event tabsactivate and then store to sessionStorage or localStorage.

$(function() {
    var selectedTabId = sessionStorage.getItem("selectedTab");
    selectedTabId = selectedTabId === null ? 0 : selectedTabId; //your default being 0
    $("#tabs").tabs({
        active: selectedTabId,
        activate : function( event, ui ) {
            selectedTabId = $("#tabs").tabs("option", "active");
            sessionStorage.setItem("selectedTab", selectedTabId);
        }
    });
});
atlmag
  • 71
  • 1
  • 4
  • Thanks, cut and paste example worked for me as long as the default ID name is tabs on your div. I just changed to localStorage so it works in a webfarm (multiple web servers) scenario. – moto_geek Feb 03 '21 at 16:43
5

Using localStorage feature of HTML5 gives the solution for the problem, and is now the recommended way to do this type of thing. Cookies cause extra data to be added to every web request and response.

You'll find that localStorage is supported by browsers as archaic as IE8, and if you really really want support for IE6 and IE7, there is a shim to do that.

HTML

<div class="mytab" id="mytab_1">
 <ul>....</ul>
 <div id="xx1">...</div>
 ...
</div>

JS

currTabIndex=sessionStorage['mytab_1'];

And the tabfuntion call

$('.mytab').tabs({
 active:currTabIndex,
 load:function(event,ui){
  sessionStorage[''+this.id]=(ui.panel.index()-1);
 }
});

Hope this would be helpful.

NealeU
  • 1,264
  • 11
  • 23
  • I think you want to use the `activate` event rather than the `load` event. – nullability May 30 '14 at 19:47
  • This worked really well. I tweaked it a tiny bit though. I used: activate: function(event, ui) { sessionStorage['rem_tab']=(ui.newTab.index()); } Then var tabIndex = sessionStorage['rem_tab']; And then active: tabIndex – dudeman Mar 13 '15 at 17:37
  • The link for the "shim" to add localStorage to IE6 and IE7 is broken, but I found one that works for me: https://gist.github.com/remy/350433 – John Lee Oct 06 '15 at 19:55
4

Simply:

activate: function(event, ui) {        
    localStorage.setItem("accIndex", $(this).tabs("option", "active"))
},
active: parseInt(localStorage.getItem("accIndex"))
meskobalazs
  • 15,741
  • 2
  • 40
  • 63
Suba Levi
  • 41
  • 2
1

You can set the active tab using the active option such as

$( ".selector" ).tabs({ active: 1 });

There are many ways to pass values to a webpage other than cookies. You can use query parameters and hidden fields for example. You would then create an onload script that would read either example using jQuery's onload example. $(function () { }).

To read query strings check out this page which gives you the method

Jquery read query string

function getParameterByName( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

and to read a hidden field.

$( ".selector" ).tabs({ active: $('#my-hidden-fiel').val() });

I agree with jquery ui's decision to remove this feature as cookies should really only be used to persist sessions in my opinion and not form fields or tabs for example.

Community
  • 1
  • 1
RyanFishman
  • 695
  • 5
  • 13
  • +1 Also note if you indicate the tab's id in the url hash, that tab will automatically open without any custom onready code. – keithjgrant Jan 14 '13 at 04:29
  • I appreciate your input on this. The hidden field might be the way to go. Like I said though, I do not want to set the active tab, I want the USER to be able to select the active tab and keep using that same tab across multiple pages. I am confused though, you have told me how to GET the parameter.... but how do I SET the parameter that the user chooses? – PaulHanak Jan 14 '13 at 04:42
  • 1
    When the user switch pages, post the hidden value to the new page using form post. Keep the hidden field up to date as the user switches tabs using the event activate as documented here. http://api.jqueryui.com/tabs/#event-activate – RyanFishman Jan 14 '13 at 04:56