Jquery Tool: Keep selected tab on refresh or save data
Asked Answered
U

3

9

I am using jquery tool for tab Ui,

Now I want to keep tab selected on page reload. Is there any way to do that? below is my code

$(function() {
    // setup ul.tabs to work as tabs for each div directly under div.panes
    $("ul.tabs").tabs("div.panes > div");
});
Undergraduate answered 2/3, 2012 at 7:46 Comment(1)
For bootstrap, solutions are discussed at https://mcmap.net/q/88059/-how-can-i-keep-selected-bootstrap-tab-on-page-refresh/873282Kassie
F
7

Here is a simple implementation of storing the cookie and retrieving it:

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

Then, to save/retrieve cookie data with jQuery UI Tabs:

$(function() {
   // retrieve cookie value on page load
   var $tabs = $('ul.tabs').tabs();
   $tabs.tabs('select', getCookie("selectedtab"));

   // set cookie on tab select
   $("ul.tabs").bind('tabsselect', function (event, ui) {
      setCookie("selectedtab", ui.index + 1, 365);
   });
});

Of course, you'll probably want to test if the cookie is set and return 0 or something so that getCookie doesn't return undefined.

On a side note, your selector of ul.tabs may be improved by specifying the tabs by id instead. If you truly have a collection of tabs on the page, you will need a better way of storing the cookie by name - something more specific for which tab collection has been selected/saved.

UPDATE

Ok, I fixed the ui.index usage, it now saves with a +1 increment to the tab index.

Here is a working example of this in action: http://jsbin.com/esukop/7/edit#preview

UPDATE for use with jQuery Tools

According the jQuery Tools API, it should work like this:

$(function() {
   //instantiate tabs object 
   $("ul.tabs").tabs("div.panes > div");

   // get handle to the api (must have been constructed before this call)
   var api = $("ul.tabs").data("tabs");

   // set cookie when tabs are clicked
   api.onClick(function(e, index) {
          setCookie("selectedtab", index + 1, 365);
   });     
   // retrieve cookie value on page load
   var selectedTab = getCookie("selectedtab");

   if (selectedTab != "undefined") {
    api.click( parseInt(selectedTab) ); // must parse string to int for api to work
   }

});

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

Here is a working (unstyled) example: http://jsbin.com/ixamig/12/edit#preview

Here is what I see in Firefox when inspecting the cookie from the jsbin.com example:

enter image description here

Flatiron answered 6/3, 2012 at 16:28 Comment(15)
I already have one cookie js which I am using for list-grid layout. Can I use same js for back-end (wordpress) as I am using this tab layout for back-end.Undergraduate
back-end? My answer will help guide you through storing a selected jQuery UI tab and retrieving it on page load. I don't see how wordpress affects that. The js that my solution provides will work on any HTML page in a browser that supports javascript. Yes, 5 or 6 are fine or more.Flatiron
I have tried your coxe but doesn't works somehow, even it is disabling tabs as well.Undergraduate
@pixelngrain, did you change what I suggested you have to change? I have rearranged my solution and provided an example. It works unless you have cookies disabled.Flatiron
I dont know if I am doing anything wrong but it's not working. What I am doing is embedding first code into head and second code into footer. Is that the right way to do?Undergraduate
Why not put it all in the the head? I would just put it all in the <head> tag inside of a new or existing <script> tag. Did the jsbin.com example work for you? It does work because I use it on a production site.Flatiron
Alright let me try with that, but I don't know how to implement jsbin.com script with my existing script.Undergraduate
let us continue this discussion in chatFlatiron
You don't "implement" jsbin.com script, you simply copy the js I provided for you on the left of the jsbin editor and paste it into your code. You will probably have to swap out my calls to #tabs for your ul.tabs selectorFlatiron
I'm on for a bit so start a chat with me if you need more help as these comments may not be useful to othersFlatiron
I appreciate your effort by heart.I think the html structure and class/id causing the issue. My structure is different than your one and I believe that is the reason I am not getting the result. Please have a look for my structure. jsbin.com/ixamig/edit#javascript,html `please make sure I am not using jquery but jquery-tools script found here flowplayer.org/toolsUndergraduate
No still not working. I have downloaded your script and check in blank file but not working either, on refresh its going back to first tab. If you don't have any problem I can send you TeamViewer ID so you can directly check on my desktop. If you don't mind. I believe something is going wrong either side..believe myside.Undergraduate
@pixelngrain, send me the ID and I will check it out, or else start a chat. The solution works, you can verify this with a cookie inspector. See image I just posted.Flatiron
I believe you without any doubt but that is also true not working with me. If you are not online than you can add me on skype ID: pixelandgrain but I think our timing doesn't matching up. I am now in GMT +4.00 Timezone and would be able to online after 18:30 So we can check on TeamViewer or Skype. Of course if you can..Undergraduate
Thanks a lot for your great help. I would never be able to done this without your help. I really appreciate your effort and time you dedicated for me. Thanks again. Just to remind you, update the working code as you said.Undergraduate
A
3

This is what worked for me... at least I haven't run into any issues yet:

$('#tabs').tabs({
            select: function (event, ui)
            {
                $.cookie('active_tab', ui.index, { path: '/' });
            }
        });
$('#tabs').tabs("option", "active", $.cookie('active_tab'));

I'm using: jQuery 1.8.2, jQuery UI 1.9.1, jQuery Cookie Plugin.

I set the "path" because in C# I set this value in a mvc controller which defaults to "/". If the path doesn't match, it wont overwrite the existing cookie. Here is my C# code to set the value of the same cookie used above:

Response.Cookies["active_tab"].Value = "myTabIndex";

Edit: As of jQuery UI 1.10.2 (I just tried this version, not sure if it's broken in previous versions), my method doesnt work. This new code will set the cookie using jQuery UI 1.10.2

 $('#tabs').tabs({
     activate: function (event, ui) {
         $.cookie('active_tab', ui.newTab.index(), { path: '/' });
     }
 });
Archives answered 17/11, 2012 at 3:50 Comment(0)
B
1

The easiest way to survive between page refresh is to store the selected tab id in session or through any server-side script.

Only methods to store data on client side are: Cookies or localStorage.

Refer to thread: Store Javascript variable client side

Borehole answered 6/3, 2012 at 16:20 Comment(1)
I am using cookie js for my front-end and I am using this tool for back-end (wordpress). Can I use same script?Undergraduate

© 2022 - 2024 — McMap. All rights reserved.