jQuery plugins: let users choose their own effects

jQuery plugins: let users choose their own effects

How to allow users to choose their own effects in jQuery's plugins.

Yesterday a friend of mine sent me a message asking me to improve his jQuery plugin by allowing users to choose their own jQuery effects. This is something very easy to do if you know that all jQuery's elements are actually objects. What does this mean? Simply put, they accept the handy square brackets notation to access their methods and properties. And jQuery's methods are simple object's methods.

Here's the solution (note the square brackets notation):


(function($) {
    $.fn.plugin = function(options) {
        options = $.extend({
            method: 'fadeOut',
            speed: 800,
            callback: function() {}
        }, options);
        
        return this.each(function() {
            var elem = $(this);
            setTimeout(function() {
                elem[options.method](options.speed, options.callback);
            }, options.speed);
        });
    };
})(jQuery);


$('#test').plugin({method: 'slideUp'});

Really simple, isn't it? With square brackets you can actually access all the jQuery's method attached to the current element including, of course, animation and effects methods.

You can see the demo on this page.