Remembering the selected tab

Monday May 25, 2009

Getting jQuery to remember the currently selected tab when you refresh the page is not trivial, but it is doable. You will need the cookie plugin and of course, jQuery UI.

The code is simple enough:

$(document).ready(function()
{
    $("#tabs").tabs(
    {
        select: function(event, ui)
        {
            $.cookie('selected-tab', '#' + ui.panel.id);
        }
    }).tabs('select', $.cookie('selected-tab'));
});

Whenever a tab is selected, you simply set a cookie that indicates which tab you are on. When the document loads, you simply select the tab specified in the cookie.

You will need to change the cookie’s name based on which tabs you are applying this method on, otherwise it will fail whenever you have tabs on more than one page.

Comments

268 days ago Anders wrote:

Just what i’m looking for. However, it would be great if you could provide us with the corresponding html.

268 days ago Anders wrote:

Just found out that this behaviour is supported from within the tabs plugin: http://docs.jquery.com/UI/Tabs#option-cookie

Commenting is closed for this article.