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: How do I add another key to object?
Publish date: 2022-03-06 | Comments: 3

Tag: Javascript

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

Tag: Javascript

Check if div have touch another div
Publish date: 2022-03-02 | 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

How to open URL in new tab & focus on it in Javascript?
Publish date: 2021-12-22 | Comments: 1

Tag: Javascript

Simple HTML date picker is showing not showing calendar icon!
Publish date: 2022-03-01 | Comments: 2

Tag: Javascript