Skip to content Skip to sidebar Skip to footer

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 = fun

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

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

Loop Through All on Click

var box = document.getElementById('box'),
    colors = ['purple', 'yellow', 'orange', 'brown', 'black'];

box.onclick = function () {
    (functionloop(){
        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);

    (functionloop(){
        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);

      }

};

Post a Comment for "Change Background Color With A Loop Onclick"