Mauro74 Mauro74 - 4 months ago 30
Javascript Question

How to make a jquery infinite animation?

I'm trying to implement a jQuery function with an infinite loop to animate the body background with 3 colours. I cannot think of a nice and clean solution.
Something like this?

$(document).ready(function(){
$('body').animate({backgroundColor:'#ffcc00'}, 500, function(){
$('body').animate({backgroundColor:'#eeeeee'}, 500, function(){
$('body').animate({backgroundColor:'#3b5998'}, 500);
});
});
});


Any idea?

Answer

You can eliminate the nesting, but the solution is a little fatter:

var cols = "#ffcc00,#eeeeee,#3b5998".split(",")
var cPos = 0

$(document).ready(function() {
   swapC()
}    

function swapC() {
    $('body').animate({ backgroundColor:cols[cPos] }, 500)
    cPos++
    if (cPos == cols.length) {
        cPos = 0
    }
    window.setTimeout(function() { swapC() }, 500)
}