Ezio_
Ezio_

Reputation: 593

jQuery How to add class to <li> or <a> and keep it on the next page load or refresh?

I have <li> elements, containing <a> elements. When the user clicks on the <a>, it sets class 'active' to the <a> and loads the new link. But when the new link is loaded, the class 'active' disappears. How to make that when the new page comes up still to have 'active' class on the same <a>?

Thanks

Upvotes: 0

Views: 1155

Answers (3)

Johnny5
Johnny5

Reputation: 6862

If the link in question matches the page's url, you can base your code on that instead of a cookie or something.

$(function() { //The document is ready...
    $('li a[href="' + window.location.href + '"]').addClass('active');
});

Note that in this form, it only works if the link is absolute, i.e. starting with http://. If the link is relative you may want to adapt this a little bit.

Upvotes: 0

matewka
matewka

Reputation: 10148

The fastest and easiest way is to keep it in a cookie. Here's the example code how to create/read cookie: LINK

In your case you'd need to add an ID or some unique attribute for each <a> or <li> so when the page reloads, the script knows which <a> should be activated, e.g.:

HTML:

<li><a href="abc.html" data-unique-attr="123">link 1</a></li>
<li><a href="def.html" data-unique-attr="456">link 2</a></li>
<li><a href="ghi.html" data-unique-attr="789">link 3</a></li>

jQuery:

// on page load: read the cookie and activate the link
$(function() {
    var activeAnchor = readCookie('activeAnchor');
    if (activeAnchor) {
        $('li a[data-unique-attr="' + activeAnchor + '"]').addClass('active');
    }
});

// on click: set the cookie
$('li a').click(function() {
    $(this).addClass('active');
    createCookie('activeAnchor', $(this).data('uniqueAttr'));
});

Upvotes: 0

chris.tian
chris.tian

Reputation: 770

Basically you need to persist the state between page changes. You could do that in one of two ways:

  1. Session parameter: Use cookies or local storage (HTML5)
  2. Request parameter: Add a URL parameter and read it via jquery (example: http://jquery-howto.blogspot.de/2009/09/get-url-parameters-values-with-jquery.html)

Upvotes: 2

Related Questions