Gonzalo Nediani Gonzalo Nediani - 3 months ago 11
jQuery Question

Body background-color won't change while scrolling

I have this body background-color transition while scrolling using jQuery.

The code works from color 1 (which is white) to color 2 (black), and backwards as well, from color 2 to color 1.

http://codepen.io/wRancho/pen/Wxmgqx

However, color 3 or color 4 are not working, I've tried several changes on the if statements but I can't figure it out why it doesn't work with more than 2 colors.

body { height: 2400px; transition: background-color 1s ease-in; }


$(window).scroll(function() {
var scroll = $(window).scrollTop();

if (scroll == 0 || scroll < 500) {
$("body").css("background-color","white");
}
else if (scroll >= 500 || scroll < 1000) {
$("body").css("background-color","black");
}
else if (scroll >= 1000 || scroll < 1500) {
$("body").css("background-color","green");
}
else {
$("body").css("background-color","white");
}});


Thanks!

Answer

you are not using the right comparison operator instead of || use &&

here is the working js code

    $(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll < 500) {
      $("body").css("background-color","white");
    } 
    else if (scroll >= 500 && scroll < 1000) {
      $("body").css("background-color","black");
    } 
    else if (scroll >= 1000 && scroll < 1500) {
      $("body").css("background-color","green");
    }
    else {
      $("body").css("background-color","white");
    }
});

here is the codepen wokring version