lundi 25 juillet 2016

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




Aucun commentaire:

Enregistrer un commentaire