Reputation: 1398
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
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
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 :
Upvotes: 2