jvanstan jvanstan - 4 months ago 25
CSS Question

jQuery animate background color. Remove Math.random

I want to animate between an array of background colors.

I found the following code, but it uses Math.random to display the background colors in random order.

$(document).ready(function() {
setInterval(function() {
var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
var theColour = theColours[Math.floor(Math.random()*theColours.length)];
$('#branding').animate({backgroundColor: theColour}, 500);
}, 1000);
});


JSFiddle

I want to remove the Math.random and display the next color in the array.

However, if I replace Math.random, with the following, the animation doesn't proceed beyond the first color in the array.

$(document).ready(function() {
setInterval(function() {
var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
var currentColour = 0;
var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
$('#branding').animate({backgroundColor: theColour}, 500);
}, 1000);
});

Answer

Because currentColour is declared inside your setInterval function, you are creating a new currentColour variable and setting it to 0 each time the function is called. Instead move currentColour outside the function scope:

$(document).ready(function() {
    var currentColour = 0; // This variable is now shared by each function call
    setInterval(function() {
        var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
        var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
        $('#branding').animate({backgroundColor: theColour}, 500);
    }, 1000);
}); 
Comments