reza_box2002
reza_box2002

Reputation: 17

How can I switch between two background-colors using js setinterval()

How to Set two background-color in the javascript by setInterval()?

    let x = document.body;
    x.style.backgroundColor = x.style.backgroundColor === "yellow" ? "pink": "yellow";

Upvotes: 2

Views: 470

Answers (1)

sidverma
sidverma

Reputation: 1185

Try this:

var i = 0;
function change() {
  var doc = document.getElementById("background");
  var color = ["black", "blue", "brown", "green"];
  doc.style.backgroundColor = color[i];
  i = (i + 1) % color.length;
}
setInterval(change, 1000);
<div id="background">&nbsp</div>

Upvotes: 3

Related Questions