jQuery: using callback functions in plugins

jQuery: using callback functions in plugins

How to allow users to add an extra action to our jQuery plugins.

Allowing users to specify additional actions on our jQuery plugins is something that should become a must for every jQuery developer. Actions can be passed along in the form of callback functions that work on jQuery elements. Cycle is a perfect example of a superior use of callback functions. In this article we'll see a practical implementation of this feature.

Simply imagine an image slideshow with pagination. A user clicks on a link and the slideshow slides to reveal the current image. Nothing unusual here. Now we want to attach a callback function that fires on each image.

First we need to specify an option that allows the user to create a callback function:

(function($) {

    $.fn.gallery = function(options) {
        var self = this;

        options = $.extend({
            wrapper: $('#gallery-wrapper', self),
            width: 550,
            height: 330,
            paginationClass: 'page',
            onimage: function() {} // callback function
        }, options);
        
        // continues
    };
})(jQuery);

We can't specify the current image as the sole argument of our function at this point, because it would raise a JavaScript error (undefined). Instead, we can use the current image when it's defined:

var _navigate = function() {

            $('a', '#gallery-pagination').click(function(e) {

                e.preventDefault();
                var $a = $(this);
                var imageIndex = $a.data('image');
                var image = $('img', self).eq(imageIndex); // current image
                var offset = image.position().left;
                options.wrapper.animate({

                    left: -offset

                }, 1500, 'linear', function() {

                    options.onimage(image); // now the image is defined, so we can call our function

                });

            });

};

Once the image is defined in the plugin, we can use it as a normal function parameter when we call our plugin:

$('#gallery').gallery({
    onimage: function(img) {
        img.animate({
            opacity: 0.5
        }, 1000);
    }
});​

You can see the demo below.

Demo

Live demo