Adding delay between separately started animations
I have an ar开发者_运维知识库ray with image URLs I add to a page as img
tags. I add them hidden and fade them in when they are loaded. This works, but I'd like to add a bit of delay between each of them so it's not so much fading in at the same time.
function ajaxCallback(data)
{
if(data && data.images)
for(var n in data.images)
{
var image = $('<img>')
.prop(data.images[n])
.css({opacity: 0})
.appendTo('#output')
.load(imageLoaded);
}
}
function imageLoaded()
{
$(this)
.animate({opacity: 1});
}
At the moment, if they load quick enough, they will all basically fade in at once. I'd like a bit of delay between each. Tried adding a call to delay
, but that didn't seem to do much. Thinking I might have to do something with a queue or something, but can't quite get how to do this.
What's the best way to do this?
In a similar case (not related to images), I use a recursive function that extracts the first element of the array, does its work, and calls itself when it finish. In your case, you should call the function again in the callback of animate()
.
You could use setTimeout
in the imageLoaded()
method and give a random value (within some bounds) for the timer.
function imageLoaded()
{
var self = $(this);
setTimeout(function(){
self.animate({opacity: 1});
},
Math.random()*2000 //will fire sometime between 0 to 2000 milliseconds
);
}
Here's one way:
for (var n in data.images) {
$('<img>').prop('src', data.images[n]).css({ // don't forget "src"
opacity: 0
})
.appendTo('#output')
.bind('reveal', imageLoaded); // bind a custom event
}
function imageLoaded() {
$(this).animate({
opacity: 1
}, function(){ // wait until animation is done via callback
$(this).next().trigger('reveal'); // then trigger the next reveal
});
}
$('#output').find('img:first').load(function() { // when first image is loaded
$(this).trigger('reveal'); // trigger its event to start the cascade
});
Example: http://jsfiddle.net/redler/mBfpG/
精彩评论