0

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?

3
  • Is the page dynamically generated, for example with PHP? then you could simply add the class server side. Commented Jul 20, 2012 at 11:15
  • It's a Sinatra app, so the page is generated using Ruby Commented Jul 20, 2012 at 11:23
  • Can't you add the class server side by checking the current file name / URL and comparing it with the link href. Would definitely be better than cookies Commented Jul 20, 2012 at 11:25

1 Answer 1

1

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') );
});

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.