Change background color with a loop onclick
11,906
Solution 1
Here are two methods, depending on what you're up to:
Loop to Next on Click
var box = document.getElementById('box'),
colors = ['purple', 'yellow', 'orange', 'brown', 'black'];
box.onclick = function () {
color = colors.shift();
colors.push(color);
box.style.backgroundColor = color;
};
Loop Through All on Click
var box = document.getElementById('box'),
colors = ['purple', 'yellow', 'orange', 'brown', 'black'];
box.onclick = function () {
(function loop(){
var color = colors.shift();
box.style.backgroundColor = color;
if (colors.length) {
setTimeout(loop, 1000);
}
})();
};
Restarts on Next Click
var box = document.getElementById('box'),
colors = ['purple', 'yellow', 'orange', 'brown', 'black'];
box.onclick = function () {
var set = colors.slice(0);
(function loop(){
var color = set.shift();
box.style.backgroundColor = color;
if (set.length) {
setTimeout(loop, 1000);
}
})();
};
Solution 2
you want it to be animated, or delayed?
Because your example works perfectly, you are looping through all colors and it is so fast that you see only the last one.
var box = document.getElementById('box');
var colors = ['purple', 'yellow', 'orange', 'brown', 'black'];
var running = 0;
box.onclick = function () {
if(running>0) return;
for (i = 0; i < colors.length; i++) {
running++;
setTimeout(function() {
box.style.backgroundColor = colors[i];
running--;
}, 1000);
}
};
Author by
Hobbes
Updated on June 04, 2022Comments
-
Hobbes almost 2 years
here is my js fiddle : http://jsfiddle.net/pYM38/16/
var box = document.getElementById('box'); var colors = ['purple', 'yellow', 'orange', 'brown', 'black']; box.onclick = function () { for (i = 0; i < colors.length; i++) { box.style.backgroundColor = colors[i]; } };
I'm in the process of learning JavaScript. I was trying to get this to loop through each color in the array, but when i click the box (demonstration on jsfiddle) it goes to the last element in the array.
-
Jared Farrish almost 10 yearsNo problem. What I'm doing is I'm taking the first off the array (
array.shift()
), setting that as the color, and then "pushing" that color to the end. So it's like "give me the first, use it, then put it on the end". Note thatarray.pop()
differs fromarray.shift()
in that it will give you the last item;array.unshift()
will put the item at the beginning of the array. -
Jen about 4 yearsThis is a true loop, as opposed to just naming your function loop like the previous answer. The first answer gets the job done, but I think you really answered the op question and my own. tysm!