Reputation: 75
I want to highlight the current page. tried this code but is not working.. any help would be thankful and appreciated..
$(function() {
$("#site-menu li a").click(function() {
$(".current").removeClass("current");
//"this" is the element clicked on
$(this).addClass("current");
});
});
<div id="menu">
<ul id="site-menu">
<li><a href="Home_Page.aspx">home</a></li>
<li><a href="Services.aspx">services</a></li>
<li><a href="About_Us.aspx">about us</a></li>
<li><a href="Contact_Us.aspx">contact us</a></li>
</ul>
</div>
Upvotes: 0
Views: 999
Reputation: 2782
I think you should start with that:
$(function() {
var curPage = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);
$("#site-menu li a[href='" + curPage + "']").addClass("current");
});
Just improve this script to work correctly with default page (I think it's gonna be Home_Page.aspx), when it doesn't appear in URL.
Upvotes: 2
Reputation: 4190
You can also try
$("#site-menu li a").live('click',function() {
$(".current").removeClass("current");
//"this" is the element clicked on
$(this).addClass("current");
});
inside your $(document).ready(function(){})
;
Upvotes: -1
Reputation: 3221
I've create a fiddle here showing a working example.
try this (see my comments too):
$(function() {
// change to on rather than deprecated click
$("#site-menu li a").on("click", function(e) {
e.preventDefault(); // stops the a href firing
$(".current").removeClass("current");
//"this" is the element clicked on
$(this).addClass("current");
});
});
Upvotes: 0
Reputation: 55750
Try this
$(function() {
$("#site-menu li a").click(function(e) {
e.preventDefault();
$(".current").removeClass("current");
//"this" is the element clicked on
$(this).addClass("current");
});
});
Also make sure you have .current class in your CSS FIDDLE
Seems to be working when I used e.preventDefault();.
Maybe the class was being rendered back to default HTML on postback..
Upvotes: 0