Highlight current page in jquery

Jimmy is right. When you reload a page, the browser also refreshes the Javascript code, which means all the variables and settings you made will also be reset. This is why the class appears to be removed when you click on the link.

The solution here would be to modify your code to loop through all the links and compare each one to the current page’s URL. When you find a match, then call the addClass function for that link to change its colour. So, something like this should work:

$(function(){

    var pathname = (window.location.pathname.match(/[^\/]+$/)[0]);

    $('#container ul li a').each(function() {
    if ($(this).attr('href') == pathname)
    {
        $(this).addClass('current');
    }
    });
});

Note that we are calling this looping function on page load, rather than calling it when user clicks on a link… because clicking on a link will cause the page to reload which will reset all the JQuery variables.

Hope this helps.

Leave a Comment