jquery - how to determine last element being animated
I'm using jQuery's animate function to animate a series of matching elements, but I want to determine when the last matching element has finished animating before calling a new fu开发者_运维技巧nction. How would I do this? Is there a way to do it without the .each() function?
This is my code:
Using Each Function:
var imageLen = $('.option_image').length -1; //Determine index of total images
$('.option_image').each(function(index){
var imageDelay = index*delayTime;
$(this).delay(imageDelay).animate({ 'backgroundPositionY' : '0px', 'opacity' : '1'},fadeTime,function(){
$('.option_title').css('opacity','1');
if (index == imageLen){
//If all have been iterated through - perform this function
}
})
});
But what I want to do is:
$('.option_image').animate({ 'backgroundPositionY' : '0px', 'opacity' : '1'},fadeTime,function(){
if (index == imageLen){
$('.option_title').css('opacity','1');
$('#back').fadeTo(fadeTime,1);
$('#restart').fadeTo(fadeTime,1);
}
});
which obviously doesn't work because "index" is not defined.
Try using a deferred object:
$('.option_image').animate({
'backgroundPositionY': '0px',
'opacity': '1'
}, fadeTime).promise().done(function() {
$('.option_title').css('opacity', '1');
$('#back').fadeTo(fadeTime, 1);
$('#restart').fadeTo(fadeTime, 1);
});
This requires jQuery 1.6+
You could use a closure, like this:
var index = 0;
var length = elements.length - 1;
elements.animate(properties, speed, function() {
if (index == length) {
doSomeStuff();
} else index++;
});
jQuery animations are added to a queue. You could test against the size of the queue in your complete callback. I think this'll work:
$('.option_image').animate({ 'backgroundPositionY' : '0px', 'opacity' : '1'},fadeTime,function(){
if ($('.option_image').queue("fx").length === 0){
$('.option_title').css('opacity','1');
$('#back').fadeTo(fadeTime,1);
$('#restart').fadeTo(fadeTime,1);
}
});
精彩评论