user image

Mahmoud Santos
Published in : 2022-02-22

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

Javascript

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

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

 

Comments

Yasen Sayed Date : 2022-02-22

Best answers

8

Best answers

8

Try this approach,

 

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>

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

How to move a div with its content to TinyMEC editor?
Publish date: 2022-02-11 | Comments: 0

Tag: Javascript

How to get audio input and audio output as one stream?
Publish date: 2022-02-13 | Comments: 1

Tag: Javascript

How do I check if an array includes a value in JavaScript?
Publish date: 2022-02-13 | Comments: 2

Tag: Javascript

JAVASCRIPT: How do I add another key to object?
Publish date: 2022-03-06 | Comments: 3

Tag: Javascript

Javascript Add (+) issue
Publish date: 2022-02-26 | Comments: 1

Tag: Javascript

Can we add a javascript or jQuery to the URL?
Publish date: 2022-03-05 | Comments: 2

Tag: Javascript

Method refactoring to avoid to many npe checks
Publish date: 2022-03-05 | Comments: 0

Tag: Javascript