Question

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

Was it helpful?

Solution

Try this with attribute-equals-selector/

  $(window).scroll(function () {
      $('.menu a.active').removeClass('active');
      $('.menu a[href="' + window.location.hash + '"]').addClass('active');
  });

OTHER TIPS

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");
               } 
           });
    });

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");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top