Tips for Writing Good jQuery Plugins

   

If you are JavaScript or web developer , you probably know jQuery. It wouldn’t be wrong to say that it is the lifeline for front end developer these days. Any good web developer would be able to work with Jquery but writing a good Jquery plugin is like an art. Here are some tips to write good Jquery plugins.

Always Put Your Code in a Closure

jQuery is a JavaScript Library that comprises of a number of features. Sometimes we also use other third party plugins in our application which can which can have same function or method which you have in your own plugin. So it’s a good idea to keep all your code within the closure to avoid.

(function($)
{    //code here
})(jQuery);
Don’t Break the Chain

One of the great features of JavaScript/jQuery is that you can just chain one function after another So we should always return the current element unless our plugin returns a value, the last line of our plugin function must be:

$.fn.pluginName = function(options)
{
    return this.each(function()
    {
        var element = $(this);
    });
}

this ensures method calls can be chained, e.g.
$(“div#container”).plugin1().plugin2().plugin3();

Make the plugin Easy to Use

In most cases, our plugin should work without the help of developer, set options or any overriding option should be pass through settings or options.
If possible make the plugin initialize itself.

(function($) {
    $.fn.pluginName = function(options) {
        var defaults = {
            color: "white",
            'background-color': "#556b2f"
        };
        var settings = $.extend({}, defaults, options);
       
        // public methods 
        this.initialize = function() {
            // do something ...
            return this;
        };
        this.myPublicMethod = function() {
            // do something ...
        };
        return this.initialize();
    }
})(jQuery);

We can initialize the above plugin as below:

$(function() {
		$("#SomeElement").pluginName();
});

Use Suitable Namespace, Naming convention
There are so many jQuery plugins. If we are writing a jquery plugin there is a strong possibility that it has been used already. So we should use suitable and proper namespace and naming convention.

Always Set Default Parameters

In our plugin at TFTH we required some input or parameters which can be passed through initialization method. But what if user has not provided any parameters?
There to avoid the undefined error we should always set default parameters.

(function($) {
    $.fn.pluginName = function(options) {
        var defaults = {
            color: "white",
            'background-color': "#556b2f"
        };
        var settings = $.extend({}, defaults, options);
        return this.css({
            color: settings.color,
            'background-color': settings.background - color
        });
    };
}(jQuery));

Initialization of plugin as below

var options = {
            color: "blue",
            'background-color': "#333"
        };

$('#container').pluginName(options);
Support HTML Parameters to make more user friendly

It is good idea to support html parameters so that plugin can be more user friendly .
We can use html5 data attribute or custom attribute as is outlined here

(function ($) {
    $.myplugin = $.myplugin || {};
    $.MyPlugin = function ( options) {
        var defaults = {
            'option1':'value1',
            'option2':'value2',
            onInit: function () {
            }
        };
        var myplugin = this, opt = {};
        var onInit = function() {

        };

        myplugin.init = function () {
            opt = $.extend(true, {}, defaults, options);
            var dvMainContainer = $(el);
            opt.option1 = dvMainContainer.data('option2');
            onInit = opt.onInit;
            onInit();
           
        };
        myplugin.init();
    };
    $.fn.myplugin = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('myplugin')) {
                var plugin = new $.MyPlugin(this, options);
                $(this).data('myplugin', plugin);
            }
        });
    };
})(jQuery);

<div id="container"  data-option2="value from html option">

</div>

<div id="container"  plugin-option2="value from html option">

</div>

Initialization of plugin as below

var options = {
            option1': “value from option”
        };

$('#container'). myplugin(options);
Adding public methods

There are many chances when we required passing some value or communicating to the plugin after the initialization. So to provide this type of functionality we should add some public methods which can be called from outside the plugin

(function($) {
  $.fn.pluginName = function() {
   // public methods
   this.initialize = function() {
    // do something ...
    return this;
   };
   this.myPublicMethod = function(params) {
    // do something ...
   };
 this.initialize();

})(jQuery);
Accepting Options for plugin customization

In many cases we required to customize plugin options as per the user requirement but what if we our plugin does not support to accepting options or param

(function($) {
    $.fn.pluginName = function(options) {
        var defaults = {
            color: "white",
            'background-color': "#556b2f"
        };
        var settings = $.extend({}, defaults, options);
        return this.css({
            color: settings.color,
            'background-color': settings.background - color
        });
    };
}(jQuery));
Use a Good Template

And last but not least we should consider to use a good template / jQuery Plugin Patterns.

;(function ($) {
    $.myplugin = $.myplugin || {};
    $.MyPlugin = function ( options) {
        var defaults = {
            'option1':'value1',
            'option2':'value2',
            onInit: function () {
            }
        };
        var myplugin = this, opt = {};
        var onInit = function() {

        };

        myplugin.init = function () {
            opt = $.extend(true, {}, defaults, options);
            var dvMainContainer = $(el);
            opt.option1 = dvMainContainer.data('option2');
            onInit = opt.onInit;
            onInit();
           
        };
        myplugin.init();
    };
    $.fn.myplugin = function (options) {
        return this.each(function () {
            if (undefined == $(this).data('myplugin')) {
                var plugin = new $.MyPlugin(this, options);
                $(this).data('myplugin', plugin);
            }
        });
    };
})(jQuery);

Few more points under this heading would be –

– This template plugin is wrapped in an enclosure.
– Supports default options which are overridden by input parameters.
– Each element is passed to each loop function as a jQuery object. Object value is stored in data attribute which can be accessed anytime
– Auto initialization code is called in the end.

I am sure if you follow these tips, your Jquery plugin will be a piece of art that will stand the test of time.

Author: Rajesh Kumar is a full stack developer who carries more than a decade experience. He is currently associated with an Assignment Help Australia company as Engineering Lead.

DMCA.com Protection Status