Search code examples
jquerycallbackjquery-callback

jQuery calling callback on jQuery plugin


I have added callback to my jQuery plugin.

$.fn.myPlg= function(options, callback) {
    if(callback) {
       //do stuff
    }
}

How now call this callback from jQuery e.g

$(document).myPlg( function(){

// how to call callback?

});

Solution

  • This will cause the callback function to execute:

    $.fn.myPlg= function(options, callback) {
        if(callback) {
           callback();
        }
    }
    

    As Samich said, you should use an options object, even if the callback is your only option. That way you can add more options easily.

    doing it that way would look like this:

    $.fn.myPlg= function(options) {
        if(options.callback) {
           options.callback();
        }
    }
    

    and

    $(document).myPlg({
       callback: function() { 
         // callback logic here
       } 
    });