Lovelock
Lovelock

Reputation: 8085

Only run function after custom function complete jQuery

I normally do e.g.:

$(".item").fadeIn(function(){
    alert('done');
});

Which works? (I believe is correct?) but how do I do this with custom functions?

E.g.

$(".item").customFunction(function(){
    customFunctionTwo();
});

Upvotes: 1

Views: 436

Answers (2)

Joy Biswas
Joy Biswas

Reputation: 6527

I guess you should be looking at promises https://api.jquery.com/promise/

$.fn.customFunction = function (callback){
    var myFn = function(){
        /* your code along with settimeout as well if you choose*/
        //example
        return $( "div" ).fadeIn( 800 ).delay( 1200 ).fadeOut();
    }
    $.when( myFn() ).done(function() {
        callback();
    });
}    

$('.item').customFunction(function () {
    customFunctionTwo();
});

Upvotes: 0

Andrey
Andrey

Reputation: 4050

Basically it will look like this

$.fn.customFunction = function (callback){
    //some code
    callback();
}
$('.item').customFunction(function () {
    customFunctionTwo();
});

Upvotes: 4

Related Questions