3gwebtrain
3gwebtrain

Reputation: 15303

Highlight current page in jquery

I have the 12 html pages. and all this pages are loads when the left navigation bar link clicked. in this, i need to add a class to the current link, which is clicked and loaded the page. i tried with this:

$(function(){
    $('#container li a').click(function(){
        $('#container li a').removeClass('current');
        var pathname = (window.location.pathname.match(/[^\/]+$/)[0]);
        var currentPage = $(this).attr('href');

        if(currentPage==pathname){
            $(this).addClass('current');
        }
        else{
            alert('wrong');
        }

       // alert(pathname+' currentPage: '+currentPage);

    })
})

it works, but on page load, the class is removed, i don't know why it's happening..

any help?

Upvotes: 3

Views: 9533

Answers (3)

Fenton
Fenton

Reputation: 251242

With jQuery, I always think it is better to use the jQuery selector to filter the elements you wish to affect, rather than looping through them yourselves. Here is my solution:

$(document).ready( function () {
    var pathname = (window.location.pathname.match(/[^\/]+$/)[0]);
    $("#container li a").removeClass("current");
    $("#container li a[href='" + pathname  + "']").addClass("current");
});

Upvotes: 6

Bug Magnet
Bug Magnet

Reputation: 2668

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.

Upvotes: 6

Jimmy
Jimmy

Reputation: 37131

JavaScript is a client side language in the browser so any changes you make to a page last only until the window is closed or a new page is loaded. What you're attempting should really be done on the server side. If you insist on using JavaScript or if a server side language is somehow not available to you, you'll need to highlight the current page's navigation link when the page loads instead of in response to clicking on one of the links.

Upvotes: 0

Related Questions