Harry F
Harry F

Reputation: 122

jQuery - correct way to wait for fade to finish

I have a problem where I want to fade out an image, then move the image to an empty <li> container. However, the image doesn't fade, instead it just seems like the fade is being overridden by the move, using html().

Below is what I'm trying to do. Is there a way I can force the move to wait for the fade to complete?

// Fade out image to be replaced
mosaic_box.find('img').fadeTo(7000, 0.0)

// Then move the image
$('.mosaic_list li:empty', obj)
    .random(1)
    .html(mosaic_box.find('img')
        .addClass('mosaic_last_img')
    );

Upvotes: 7

Views: 4569

Answers (4)

Aditya Ravi Shankar
Aditya Ravi Shankar

Reputation: 371

jQuery.fadeTo() has an optional callBack parameter.

http://api.jquery.com/fadeTo/

.fadeTo( duration, opacity [, callback] )

callback - A function to call once the animation is complete.

The simplest way to do this is using an anonymous function -

mosaic_box.find('img').fadeTo(7000, 0.0, function(){
    $('.mosaic_list li:empty', obj)
        .random(1)
        .html(mosaic_box.find('img')
        .addClass('mosaic_last_img');
    );
});

Upvotes: 2

Shawn Chin
Shawn Chin

Reputation: 86854

fadeTo(), as with most animation related methods, accept an optional callback argument which you can use to specify the function to run once the animation is completed.

To modify your code (untested):

// Fade out image to be replaced
mosaic_box.find('img').fadeTo(7000, 0.0, function() {
    // Then move the image
    $('.mosaic_list li:empty', obj)
        .random(1)
        .html(mosaic_box.find('img')
            .addClass('mosaic_last_img')
        );
});

Upvotes: 2

Richard Dalton
Richard Dalton

Reputation: 35793

Do the move in the callback from the fadeTo function:

mosaic_box.find('img').fadeTo(7000, 0.0, function() { 
    $('.mosaic_list li:empty', obj)
     .random(1)
     .html(mosaic_box.find('img').addClass('mosaic_last_img'));
});

Upvotes: 7

Keith.Abramo
Keith.Abramo

Reputation: 6955

Move your code into a function and pass that function to the callback param of fadeTo

function callback(){
                    // Then move the image
                    $('.mosaic_list li:empty', obj)
                    .random(1)
                    .html(mosaic_box.find('img')
                        .addClass('mosaic_last_img')
                        );
}

 // Fade out image to be replaced
 mosaic_box.find('img').fadeTo(7000, 0.0, callback)

Upvotes: 3

Related Questions