Skip to content
Advertisement

switching between two colors is not working

What is it that I am missing here so my page switches between these two colors? Thank you !

var body = document.querySelector("body");
var isBlue = false;

setInterval(function(){
    if(isBlue){
        body.style.background = "green";
    } else {
        body.style.background = "white"
    }
},1000);

Advertisement

Answer

You’re never changing the value of isBlue, so it’s always false, so you always set white as the background color.

Afrer the if/else, invert the flag:

isBlue = !isBlue;

E.g.:

setInterval(function(){
    if(isBlue){
        body.style.background = "green";
    } else {
        body.style.background = "white"
    }
    isBlue = !isBlue;
},1000);

Side note: “isBlue” seems an odd name for a flag that sets a green background… 😉 (Though to be fair, as I understand it in some cultures there isn’t a distinction between blue and green.)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement