Hobbes
Hobbes

Reputation: 106

Change background color with a loop onclick

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.

Upvotes: 3

Views: 16228

Answers (2)

Jared Farrish
Jared Farrish

Reputation: 49208

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;
};

http://jsfiddle.net/pYM38/17/

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);
        }
    })();
};

http://jsfiddle.net/pYM38/23/

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);
        }
    })();
};

Upvotes: 2

Luke
Luke

Reputation: 8407

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);

      }

};

Upvotes: 2

Related Questions