mheavers
mheavers

Reputation: 30168

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 function. 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.

Upvotes: 2

Views: 520

Answers (3)

Tom Hamshere
Tom Hamshere

Reputation: 502

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);
    }
});

Upvotes: 1

DNS
DNS

Reputation: 38199

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++;
});

Upvotes: 1

Kevin B
Kevin B

Reputation: 95056

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+

Upvotes: 5

Related Questions