1

Often times I come across situations where I want to execute a jQuery function or initialize a jQuery plugin like jQuery datatables and would like to have code execute after the function has finished. jQuery functions such as hide or fadein or other transformation functions take an optional callback parameter to accomplish this. However there are other jQuery functions which just return the 'this' object to allow for chaining. I would like to know if there is a way using chaining or some other method to execute some kind of generic function which takes a callback after whatever jQuery function I call finishes.

Something like:

$("#element").datatable().executeCallback(myCallbackFunction);

3 Answers 3

3

You just need a plugin which takes a function argument, applies it to everything matched by the object, and returns the object itself. A simple chainable "genericCallback" implementation:

function makeRed() {
    $(this).css("border", "1px solid red");
}

$.fn.genericCallback = function(fn) {
    if(!typeof fn === 'function') {
        console.log('Function expected, got a ' + typeof fn);   
    }
    return this.each(function() {
        fn.apply(this);
    });
};

$("div").genericCallback(makeRed);

You can try it here.

2

Take a look at jquery queue http://api.jquery.com/queue/, this might help you.

0

This isn't very robust but it does what you want for generic callbacks.

$.fn.executeCallback = function( fn )
{
    window[fn]();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.