How to write jQuery Plugin - Quick Tutorial

Any jQuery plugin would usually work on single or multiple DOM elements. Writing jQuery plugins is fairly easy. Follow these steps to create your own plugin.

All jQuery plugins have to be wrapped with in jQuery namespace.

(function (jQuery) { /* Your code will go here */ })(jQuery)

You might have many functions for a single plugin. So it is advised to create a datastructure that contains all functions related to a plugin. This keeps jQuery namespace clean from clutter.

    (function (jQuery) { 
    //All function related to this plugin
    var methods = { 
        init: function(options) { },
        work: function(args) { },
        clean: function(args) { }
     };
     })(jQuery)

Naming of function depends on you, however I will advice that name should have some meaning and should be related to what they are meant to do.

Finally you will have your plugin function which will in-turn call functions from data structure you created above.

(function (jQuery) { 
    //All function related to this plugin
    var methods = { 
        init: function(options) { },
        work: function(args) { },
        clean: function(args) { }
     };

     //Plugin function
     jQuery.fn.pluginname = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.pluginname');
        }
    }; })(jQuery)

    //example call
    $("div").pluginname();
    $("div").pluginname('work', args);
    $("div").pluginname('clean', args);
    

By default my code assumes that if you do not pass method name then you are referring to "init" method.

A little more about init method: Init method is where you initialize your plugin and set everything in place. Most probably you might have to use init method only for small plugins. options are settings that you want to use for your plugin.

var methods = { 
        init: function (options) {
            var defaultVal = {
                Prop1 : 1,
                Prop2 : 2
            };

            var obj = $.extend(defaultVal, options);
            return this.each(function () { 
            //Do Work Here 
            //each element 
            });
             }
     };

This was my short tutorial on writing your own j-query plugin. Feel free to ask questions in the comment box below. Would be more than happy to help.

Subscribe for our monthly newsletter for updated articles and useful code scripts.

Share It

comments powered by Disqus
Chat With Us Close
Leave Message