jQuery tabs and cookies

I’ve found many examples of scripts that save the selected tab inside a cookie but none of them worked out of the box… so let me write here a note and a snippet about how I got it working (big thanks to Massimiliano).

The XHTML that the snippet refers to is available on http://docs.jquery.com/UI/Tabs#source (you have to use its CSS or one of the same kind, of course).

You also need to include

  • ui.base.js
  • ui.tabs.js
  • jquery.cookie.js

The snippet (quick, dirty and raw… but working) is:


$(document).ready(function(){
  var tab_cookie_id = parseInt($.cookie("the_tab_cookie")) || 0;
  $("#example > ul").tabs({
    selected: tab_cookie_id,
    show:     function(ui) {
      var murl   = ui.tab;
      var nurl   = murl.toString().split("#");
      var ourl   = nurl[1].split("-");
      var tab_id = --ourl[1];
      $.cookie("the_tab_cookie", tab_id);
    }
  });
});

Last update: 2008-06-11

6 Comments

  1. Dave
    Posted August 9, 2008 at 12:09 pm | Permalink

    This line:
    show: function(ui) {
    should be:
    show: function(junk,ui) {
    for jquery 1.2.6 I believe. The ui object is now the second parameter.

  2. Posted August 15, 2008 at 9:51 am | Permalink

    fix some…
    work with jQuery 1.2.6 and ui-Tabs 1.5

    var tab_cookie_id = parseInt($.cookie(”the_tab_cookie”)) || 0;
    $(”#container-1 > ul”).tabs({
    selected: tab_cookie_id,
    show: function(e, ui) { var tab_id = ui.index; $.cookie(”the_tab_cookie”, tab_id, { expires: 30}); }
    });

  3. Posted August 15, 2008 at 2:55 pm | Permalink

    I rewrite for ui Tab3.0 + jQuery 1.2.6

    var tab_cookie_id = parseInt($.cookie(”the_tab_cookie”)) || 0;

    $(”#container-1 > ul”).tabs({
    selected: tab_cookie_id,
    select: function(e, ui) { if (ui.index == 0 && tab1_use_ == 1) {/* do some thing */}
    },
    show: function(e, ui) { var tab_id = ui.index; $.cookie(”the_tab_cookie”, tab_id, { expires: 30 }); }
    });

  4. Posted August 15, 2008 at 7:00 pm | Permalink

    Dave, Alien Y: thanks… I’m going to try your snippets as soon as possible and perhaps that could lead me to release an updated version of my code.

  5. PP
    Posted October 14, 2008 at 8:55 pm | Permalink

    thx Alien Y :)

  6. Posted October 20, 2008 at 2:57 pm | Permalink

    Don’t try it, just use it, it is working good..

Post a Comment

Your email is never shared. Required fields are marked *

*
*