ponens
ponens

Reputation: 85

Stop addClass from firing multiple times

I'm attempting to add a class to my navigation when a user scrolls, the class will be added to an element depending on the .scrollTop() value. I have this working fine but what is happening is that every time the user scrolls, addClass is constantly firing and because I have CSS3 animations on the class being added it creates a very obvious artefact.

See my rough implementation here

I do realise that there are options like 'scrollspy' and 'waypoints' but I'd love to find a way to implement this without them (I haven't tested to see if this occurs with those libraries)

Is there anyway to prevent this from happening? Thanks.

Edit: Attaching code as per a request.

$(window).scroll(function(){
    var scrollPos = $(window).scrollTop();
    if(scrollPos <= 100){
        $(".nav-home").addClass("selected");    
    }
    if(scrollPos > 100 && scrollPos <= 500){
        $(".nav-showcase").addClass("selected");
    }
});

Upvotes: 0

Views: 388

Answers (3)

ponens
ponens

Reputation: 85

As mentioned earlier by @Mark, "You need to read your code like a story"; I simply did not read my story with enough depth. I was removing my class at the incorrect location thus causing the problem that I had. I have corrected the snippet in the jsbin that I posted above if anyone is interested.

Thanks for all the replies.

Upvotes: 0

Mark
Mark

Reputation: 6865

You need to read your code like a story:

if(scrollPos < 100){
  $(".nav-home").addClass("selected");  
}
if(scrollPos > 100 && scrollPos < 500){
 $(".nav-showcase").addClass("selected");
}

if my scroll is smaller as 100, add the class selected on .nav-home if my scroll is between 100 && 500 add the class selected on .nav-showcase

I hope you already understand why it is firing so many times?

If not: there is a scroll between 100 - 500 (400 pixel), than could be a lot of scrolls, so it is firing all the time if you are between those 2 values.

As a solution i would say, go for MRIDA's solution:

if(scrollPos < 100){
  if(!$(".nav-home").hasClass("selected")){
    $(".nav-home").addClass("selected");
  }
}
if(scrollPos > 100 && scrollPos < 500){
  if(!$(".nav-showcase").hasClass("selected")){
    $(".nav-showcase").addClass("selected");
  }
}

Upvotes: 1

mrida
mrida

Reputation: 1157

You may check if the class is already added and if yes do not add it again.

if(!$(".nav-home").hasClass("selected")){
$(".nav-home").addClass("selected")
}

hope this helps

Upvotes: 2

Related Questions