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?
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:
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.