views:

46

answers:

1

I have a navigation tabs and when user clicks a tab the div changes with ajax. I would like to it to remember on what tab user was when user changes page. I havent done the tab navigation and im totally new to javascript/jquery. Here is the javascript for the tabs:

 jQuery('#contentContainer #tabNavi .nav-item').each(function(i, item) {
        jQuery(item).bind('click', function() {
            if (jQuery('a', this).hasClass('activeTab')) {
                return;
            } else {
                jQuery('#contentContainer #tabNavi .nav-item' a').removeClass('activeTab').eq(i).addClass('activeTab');
                channel_id = jQuery('a', this).attr('href').split('#')[1];
                if (channel_id == _channel) {
                    return;
                }

            }
        })
    });

The nav links are like this:

<li><a href="#39">Link1</a></li>
<li><a href="#53">Link2</a></li

Now I have the href value saved in a cookie but i dont know how can i change the active class to right li item when user comes on page and he has been on site before and he has clicked some tab.

+2  A: 

Put this code after click event initialization (jQuery(item).bind('click', function() {...})

var selectedTab = $.cookie('selectedTab');

if (selectedTab) {
    $('li[href="' + selectedTab + '"]').click();
}

UPD

A bit modified code

(function($) {

    $('#contentContainer #tabNavi .nav-item a').click(function() {

        var $link = $(this);
        $link.click(function() {
            if (!$link.hasClass('activeTab')) {
                $('#contentContainer #tabNavi .nav-item a.activeTab').removeClass('activeTab');
                $link.addClass('activeTab');
                $.cookie('selected-tab', $link.attr('href'));
            }

            return false;
        });

    });

    var selectedTab = $.cookie('selected-tab');
    if (selectedTab) {
        $('#contentContainer #tabNavi .nav-item a[href="' + selectedTab + '"]').click();
    }

})(jQuery);
fantactuka
But doesn't that happend after user clicks the navigation? I would like to switch to right tab automatically when the page loads.
wilhemsson
Checkout updated code
fantactuka