Liam
Liam

Reputation: 9855

Order jQuery functions, only run when last is completed

Im trying to control the order of my functions in jquery, on click id like an image to fade out, the source of the image to be swapped, and then the new image fade in.

I have the following that sort of works, only it does them all at once, is their a way to prevent this?

    // Animate height of div containing information
    $(this).animate({
        'height' : '600px'  
    },500, function(){
        $('html, body').animate({ scrollTop: $(this).offset().top });

        // Fade initial image out
        img.fadeOut();

        // Switch to hi-red image
        img.attr('src', function(i, value) {
            return '_includes/images/work/hires/' + value;
        });

        //Fade Hi res image in
        img.fadeIn();  
    });

Upvotes: 0

Views: 112

Answers (4)

techfoobar
techfoobar

Reputation: 66663

You should be able to do this with promise()

// Fade initial image out
img.fadeOut();

// Switch to hi-red image
img.promise().done(function() {
    $(this).attr('src', function(i, value) { return '_includes/images/work/hires/' + value; });
});

//Fade Hi res image in
img.fadeIn();  

Docs: http://api.jquery.com/promise/

Upvotes: 3

Binary Brain
Binary Brain

Reputation: 1211

You should use a callback function.

// Fade initial image out
img.fadeOut(duration, function () {
    // Switch to hi-red image
    img.attr('src', function(i, value) {
        return '_includes/images/work/hires/' + value;
    });

    //Fade Hi res image in
    img.fadeIn();
})

This way, once the first image had faded out, jQuery will call the anonymous function you passed as an argument.

Source: http://api.jquery.com/fadeOut/

Upvotes: 0

Magus
Magus

Reputation: 15104

fadeOut can take a complete attribute : http://api.jquery.com/fadeOut/

// Animate height of div containing information
$(this).animate({
    'height' : '600px'  
},500, function(){
    $('html, body').animate({ scrollTop: $(this).offset().top });

    // Fade initial image out
    img.fadeOut(400, function() {
        // Switch to hi-red image
        img.attr('src', function(i, value) {
            return '_includes/images/work/hires/' + value;
        });

        //Fade Hi res image in
        img.fadeIn();  
    });

});

Upvotes: 3

Seidr
Seidr

Reputation: 4936

You can use the 'queue' functionality of jQuery to queue up function calls.

http://api.jquery.com/queue/

Upvotes: 1

Related Questions