Reputation: 15
I have a code that makes my URL go like this www.mypage.com#div1
to www.mypage.com#div2
when I scroll down the page. To get my menu items highlighted as I scroll down the page, I've written this code which works fine:
$(window).scroll(function() {
$(".menu a").each(function() {
if (this.href == window.location.href) {
$(this).addClass("active");
} else {
//Something here?
}
});
});
But the thing is that I want to remove the "active"-class again. I tried putting all sorts of things in the "else"-section, but nothing seems to work.
Any help would be greatly appreciated!
Thanks, Tina
Upvotes: 1
Views: 761
Reputation: 32581
Try this with attribute-equals-selector/
$(window).scroll(function () {
$('.menu a.active').removeClass('active');
$('.menu a[href="' + window.location.hash + '"]').addClass('active');
});
Upvotes: 1
Reputation: 74738
I suggest you to change your if condition to this and see if it solves:
if (this.href == window.location.hash) {
$(this).addClass("active");
} else {
$('.active').removeClass("active");
}
Upvotes: 0
Reputation: 8781
This should work:
First of all remove the active class and then assign it to an appropriate div
$(window).scroll(function() {
$(".menu a").each(function() {
$(".active").removeClass("active");
if (this.href == window.location.href) {
$(this).addClass("active");
}
});
});
Upvotes: 0