Viszman
Viszman

Reputation: 1398

change background image in loop

i want to change background image of page using jQuery onclick would look like this:

var colors = ['blue', 'green', 'yellow', 'black'];
$('#click').click(function(){
    $('body').css('background', colors[1]);
})

but i want to change it automatically using some short of 'jQuery` function, my try so far is this :

var colors = ['blue', 'green', 'yellow', 'black'];

$.each(colors, function(color){
    setTimeout(function(){$('body').css('background', color)}, 1000);
});

but it doesn't work, any help would be appreciated

Upvotes: 1

Views: 1406

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

Try

var colors = ['blue', 'green', 'yellow', 'black'],
    colorIndex = 0,
    $body = $('body');

setInterval(function(){ $body.css('background', colors[colorIndex++ % colors.length])}, 1000);

Demo at http://jsfiddle.net/gaby/8uZga/

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382092

You can do this :

var colors = ['blue', 'green', 'yellow', 'black'];

$.each(colors, function(i, color){
    setTimeout(function(){$('body').css('background', color)}, (i+1)*1000);
});

I made two changes :

  • the first argument given to the callback is the index, not the element of the array
  • I give different delays using the index to compute the delay

Upvotes: 2

Related Questions