kcrocks
kcrocks

Reputation: 21

animate background color multiple times.

I am trying to animate the background color of a div multiple times on different scrolltop value. Below is the code I have, but it only changes the color once (it only listens to the second one.) can anyone help?

$(window).scroll(function() {
         if($(window).scrollTop() >=200){
             $('#div01').stop().animate({ backgroundColor: "#fff" },500);
         }
         else{
             $('#div01').stop().animate({ backgroundColor: "#333" },500); 
         }
});
 $(window).scroll(function() {
         if($(window).scrollTop() >=500){
             $('#div01').stop().animate({ backgroundColor: "#777" },500);
         }
         else{
             $('#div01').stop().animate({ backgroundColor: "#fff" },500); 
         }
});

Upvotes: 0

Views: 82

Answers (2)

knrz
knrz

Reputation: 1811

I have a feeling that your second $(window).scroll() is overriding the first one. The following code should work.

$(window).scroll(function() {
         if($(window).scrollTop() >= 500){
             $('#div01').stop().animate({ backgroundColor: "#777" },500);
         }
         else if($(window).scrollTop() >=200){
             $('#div01').stop().animate({ backgroundColor: "#fff" },500);
         }
         else{
             $('#div01').stop().animate({ backgroundColor: "#333" },500); 
         }
});

In any case, this is a more DRY version of your code.

Upvotes: 1

Felix
Felix

Reputation: 38112

Give another condition for your first if to check if $(window).scrollTop() less than 500:

if($(window).scrollTop() >=200 && $(window).scrollTop() < 500){
    $('#div01').stop().animate({ backgroundColor: "#fff" },500);
}
else{
    $('#div01').stop().animate({ backgroundColor: "#333" },500); 
}

Upvotes: 2

Related Questions