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

Adding an id number at the first index to an array of objects
Publish date: 2022-02-13 | Comments: 1

Tag: Javascript

JavaScript variable for Changing CSS Height
Publish date: 2022-02-12 | Comments: 1

Tag: Javascript

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

Tag: Javascript

Vanilla JavaScript Next & prev Navigation
Publish date: 2022-02-22 | Comments: 1

Tag: Javascript

How select specific tag in jQuery using if else statement?
Publish date: 2022-02-27 | Comments: 1

Tag: Javascript

What is the use of package-lock JSON file?
Publish date: 2022-02-11 | Comments: 3

Tag: Javascript

Can I read a local json, image or text file from Javascript?
Publish date: 2022-03-03 | Comments: 1

Tag: Javascript