Question

I was wondering what is the best way to perform a second function after the first one is done.

For example make an animation and then fadeIn another element:

$('.btn').click(function () {   
$("#div1").animate({
    marginTop: - 100
    }, "slow");
    $("#div2").fadeIn();
});

This fades in the Div2 and at the same time it animates the div1. Some people use delay() but that's not a very good solution because some browsers act differently etc.

Can you suggest a good solution to this please? Thanks

Was it helpful?

Solution

If you're using a built-in function like animate you can leverage it's callback function (which is executed once the animation is complete) like this:

$('#div1').animate({marginTop: -100}, "slow", function() {
    $('#div2').fadeIn();
});

If you're creating your own function; you can pass the callback function to it like this:

function doSomething(param, fn){
    // Do something with function

    // Execute Callback Function //
    if (typeof fn == 'function') {
        fn.call(this); // Give Function Scope
    }
}

doSomemthing(
    param,
    function(){
        // Callback Function Goes Here
    }
)

I hope this helps!

OTHER TIPS

animate [docs] accepts a third argument, a callback function which is executed once the animation is complete:

$("#div1").animate({marginTop: - 100}, "slow", funciton() {
    $("#div2").fadeIn();
});

You can perform div2.fadeIn() in the complete function of animate for div1.

    $('.btn').click(function () {   
$("#div1").animate({
    marginTop: - 100
    }, "slow", function() {;
    $("#div2").fadeIn();});
});

You can use Callbacks. As soon as the first function has returned, the second one is started. You can chain as many callbacks as you want.

@felix-kling has an example in his post

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top