2

Lets say we have a side bar on a page. It has two tabs. When you click the unselected tab, the content below it in the sidebar instantly switches using jQuery. The old div is hidden, the new div is shown. Not a big deal.

Now that you've selected that div however, when you click to the next page, the history of that selection is lost, and you're back to the first default selected div.

How can I keep the action persistent?

vzwick
  • 11,008
  • 5
  • 43
  • 63
Elliot
  • 13,580
  • 29
  • 82
  • 118

2 Answers2

0

Use a cookie to keep track of which tab is selected.

$.cookie('tabSelected', 'news');

On pageload select automatically the tab from cookie value or the default value if no cookie is set. You can find jQuery cookie plugin here

This is assuming that the tab thing is just a small user preference, not the whole site navigation mechanism.

Esailija
  • 138,174
  • 23
  • 272
  • 326
0

You might want to look into jQuery Cookie.

Assuming HTML along these lines:

<ul class="tabs">
    <li class="tab" id="tab1">
        ...
    </li>
    <li class="tab" id="tab2">
        ...
    </li>
</ul>

this would work:

$(document).ready(function(){
    $('.tab').click(function(){
        // show correct tab, hide other tabs ...
        $.cookie('selected_tab', $(this).attr('id')); // save information in a cookie
    });

    current_tab = $.cookie('selected_tab'); // read and cache information from cookie

    if (current_tab != null)
    {
        $('#' + current_tab).trigger('click'); // trigger the tab click handler, thereby restoring the tab
    }
});

Another option would be to attach an anchor to each link's URL that signifies the currently selected tab and evaluate it on page load:

$(document).ready(function(){
    $('.tab').click(function(){
        // show correct tab, hide other tabs ...

        var current_id = $(this).attr('id'); // cache the current tab id

        $('a').each(function(i,e){ // add a hash '#tab=tab1' to each link in the page
            hrf = $(e).attr('href');
            if (hrf) {
                $(e).attr('href', hrf.split('#')[0] + '#tab=' + current_id);
            });
        });
    });

    current_tab = document.location.hash.split('tab=')[1];

    if (current_tab)  // if '#tab=foo' is present in the URL
    {
        $('#' + current_tab).trigger('click'); // trigger the tab click handler, thereby restoring the tab
    }
});

This approach obviously has its own problems, though (i.e. the inability to use hashed links as those get overwritten).

vzwick
  • 11,008
  • 5
  • 43
  • 63
  • look at your own revision history lol. – Kenan Banks Nov 05 '11 at 13:40
  • 1
    @Triptych Yeah, I was initially going to wrap all of my answer into an "either ... or" statement, but I guess that's bad practice :p (Does anyone else catch himself treating plain text as if it was code?) – vzwick Nov 05 '11 at 13:45