3

I've been trying to come up with the most concise way that I can possibly change background colors using JavaScript. (Trying to get the hang of forEach and higher order functions just for fun.) Anyway, this will run on page load, and I think I'm pretty close:

function background(){ var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"]; function change(newcolor){ document.body.style.backgroundColor=newcolor; } colorArray.forEach(function(color){ setTimeout(change(color), 1000); }); } 

The problem is that the background color is only showing the last element in the array. I also am not sure how to start the forEach loop over again when it is has finished. Thanks for any help!

1
  • Do you have to use JavaScript? What about CSS transitions and keyframes? Commented Jan 8, 2016 at 5:09

3 Answers 3

6

Like this ... Also can ...

var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"];

var count = 0;

 function change() { document.body.style.backgroundColor = colorArray[count]; count++; if(count == colorArray.length) { count = 0; } } setInterval(function(){ change(); }, 1000); 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, and just for fun with your solution, if we want to loop more smoothly e.g. 1234554321 vs 123451234 I added: colorArray.reverse(); right before the count reset. cheers YLS!
2

The problem is you are passing the value returned by change as the timeout handler, instead you need to pass a function reference.

If you want to have an infinite loop, then you can use setInterval() like

function background() { var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"]; function change() { index = index >= colorArray.length ? 0 : index; document.body.style.backgroundColor = colorArray[index++]; } var index = 0; var interval = setInterval(change, 1000); } background();


If you want to use setTimeout() itself and want to iterate only once then you can use

function background() { var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"]; function change(newcolor) { document.body.style.backgroundColor = newcolor; } colorArray.forEach(function(color, i) { setTimeout(change.bind(undefined, color), i * 1000); }); } background();

2 Comments

That was an awesome answer. Can you explain a little bit about what: index = index >= colorArray.length ? 0 : index; is doing?
@Trevor That is to reset the index to 0 once we reach the last item in the array
1

Improving ....

var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"]; var count = 0; setInterval(function(){ document.body.style.backgroundColor = colorArray[count]; count++; if(count == colorArray.length) { count = 0; } }, 1000); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.