Reputation: 5141
I'm developing a menu. This menu, will change the background image when you click on a link, as almost all menus do. If I click in one link from the menu, this link background will change the color.
My jQuery script is:
$(function() {
$('#menu ul li').click(function() {
$('#menu ul li').removeClass("current_page_item");
$(this).addClass("current_page_item");
//return false;
});
});
Today, with the "return false" commented, when I click on the link under "#menu ul li" it changes the background open the new page and the background is reset. For sure, if I uncomment the return false
, the background works fine but then I cannot open any links. So it looks like after that I open a new page, it resets the classes. How can I make it persistent?
Upvotes: 1
Views: 166
Reputation: 5239
You'll want to do this after the page loads rather than before. You could do it server side as Jud suggests or use a jQuery script like the one below. This little script has been my preferred method as of late.
var path = location.pathname.substring(1);
if(path){
$('#menu a[href="' + path + '"]').attr('class', 'current');
$('#subnav a[href="' + path + '"]').attr('class', 'current');
}
Upvotes: 1
Reputation: 11595
Dynamically added classes won't persist between page loads. Consider using some server side code to add the class current_page_item
as needed.
Upvotes: 3