Richard Stokes
Richard Stokes

Reputation: 3552

CSS jQuery Active Tab Selection

I've a navigation bar on my page, containing links that I would like to style differently if they are the last clicked link. I've set up my CSS like this:

#nav li a.active {
  background-color: #F2F2F2;
  color: #000000;
  font-weight: bold;
}

and I have a jQuery script in my layout file that looks like this:

$('#nav li a').click(function() {
  $('#nav li a.active').removeClass('active');
  $(this).addClass('active');
});

Whenever I click a link, I get the desired effect, but only until the next page loads. When the next page loads, the link I just click does not have the .active css class. How can I make this class persist between different pages?

Upvotes: 0

Views: 467

Answers (1)

Satya Teja
Satya Teja

Reputation: 616

For retaining the values you can use javascript cookies

Download and include the plugin from here https://github.com/carhartl/jquery-cookie

and add this JS

document.ready(function(){

if($.cookie( "prev") != '')
{
$('#'+ $.cookie( "prev")).addClass('active');
}

$('#nav li a').click(function() {
  $('#nav li a.active').removeClass('active');
  $(this).addClass('active');
$.cookie( "prev", $(this).attr('id') );
});

});

Upvotes: 1

Related Questions