Reputation: 11
I need to change the background for the menu item of the active page. I trying to achieve this with JQuery and CSS.
My code is: HTML
<ul class="nav">
<li id="header"><a href="Default.aspx">Home</a> </li>
<li>|</li>
<li><a href="About.aspx">About</a> </li>
</ul>
CSS
.nav li.active {
background-color:green;
}
.nav li.active a {
color:#fff;
font-weight:bold;
background-color:green;
}
And finally the JQuery I am using for this is as below.
$(function () {
setNavigation();
/* below statement is just to verify if jquery working at all*/
$('#header').css("background-color", "green");
});
function setNavigation() {
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$(".nav a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.length) == href) {
$("a").closest('li').addClass('active');
/* below statement is just to verify if jquery working*/
$('#header').css("background-color", "green");
}
});
}
I tried to debug this is using firebug still couldn't find the mistake. I'm a newbie to JQuery and This is not working (might be a silly mistake) :( Can anyone please help me with this?
Upvotes: 1
Views: 90
Reputation: 11148
When you're in an .each
loop, $(this)
refers to the object currently being iterated on. You want to add the class to the current anchor, not all anchors. So, you're going to want to change the following line:
Change $("a").closest('li').addClass('active');
To this line:
$(this).closest('li').addClass('active');
Upvotes: 2
Reputation: 19750
$("a").closest('li').addClass('active');
will always do the same thing regardless of what page you're on. It will add the active
class to every li
which has an anchor as a child, because you're selecting every anchor on the page with $("a")
.
Perhaps you wanted something like this:
$(this).closest('li').addClass('active');
Upvotes: 2