jQuery: How to create a new plugin

Basic template:
The following template is a basic plugin. You can change the name “PluginName” to whatever you want, add or remove arguments and add of course your code!

//Map JQuery to the dollar sign (to avoid overrides)
(function( $ ){
    //Name and params
    $.fn.PluginName = function(a1, a2, ...) {
       ...
    };
})( jQuery );

//Usage
$("...").PluginName("arg1", "arg2", ...);

You can continue reading more information on plugin creation that include:

  • Use of ‘this’ keyword
  • Maintaining chainability
  • Default options/settings
  • Enforcing encapsulation
  • Binding and unbinding events

1. Using ‘this’ and maintaining chainability:

(function( $ ){
    $.fn.PluginName= function(a1, a2, ...) {
        //'this' is a JQuery Object, no need for $(this)
       this.children().each( function(){
           //But now 'this' is a DOM element, a "child" of "this.children()"
           $(this).DoSomethingGreat(a1+a2);
       });
       //'return' to maintain chainability
       return this;
    };
})( jQuery );

//Usage, OtherMethod() can be called because of the return
$("...").PluginName("arg1", "arg2", ...).OtherMethod();

2. Setting default options, and passing new ones

(function( $ ){
    $.fn.PluginName = function(o) {
        //Use of extend to merge default options with new ones
        var options = $.extend( {
                                 'option1' : 'value1',
                                 'option2' : 'value2'
                                }, o);
    };
})( jQuery );

//Usage, override only option1
$("...").PluginName({'option1' : 'newvalue'});

3. Enforcing encapsulation in JQuery:

(function( $ ){
    //Methods
    var methods = {
        method1 : function( ) {...},
        method2 : function( a1 ) {...},
        method3 : function( options ) {...}
    };

    $.fn.PluginName = function( method  ) {

        //Is there method with this name?
        if ( methods[method] ) {
            //Call method and pass the arguments
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1));
        }
        //"Default" method, when no method name is passed, calls method3
        else if ( typeof method === 'object' || ! method ) {
            //Call default method (e.g. method3) and pass args
            return methods.method3.apply( this, arguments );
        }
        //Wrong method
        else {
            //Error Handling
        }
    };

})( jQuery );

//Usage, default method, calls method3
$("...").PluginName();
//Usage, calls method3
$("...").PluginName({'param1':'value1'});
//Usage, calls method1
$("...").PluginName('method1');
//Usage, calls method1
$("...").PluginName('method2', 'value1' );

4. Binding and unbinding events:

(function( $ ){
//Methods
    var methods = {
        init : function( ) {
            //bind in namespace ".PluginName"
            $("...").bind('click.PluginName', methods.method3 );
            $("...").bind('mouseover.PluginName', methods.method3 );
        },
        destroy: function( ) {
            //unbinds all
            return this.each(function(){
                $(window).unbind('.PluginName');
            })
        },
        method3: function(){...}
    };
    $.fn.PluginName = function( method  ) {
        ...//Call methods as described in 3
    };
})( jQuery );

//Usage, Binds event
$("...").PluginName();
//Usage, Unbinds event
$("...").PluginName('destroy');

More reading: http://docs.jquery.com/Plugins/Authoring

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s