Enter your keyword

Writing a jQuery Plugin – Starter Template

Writing a jQuery Plugin – Starter Template

Writing a jQuery Plugin – Starter Template

Plugins are reusable portions of code which help you write even less Javascript to achieve specific features on the client side. You can make your own plugins and use them privately in your code or you can release them into the wild. There are thousands of jQuery plugins available online to do almost whatever you need it to do.

But what if you can’t find just the right plugin to suit your needs? Or you’re just looking to keep your project DRY by combining some oft-used functionality into one nice, neat package? The solution might be to roll your own plugin to meet exactly your needs.

Writing your own jQuery plugin isn’t as hard as it might seem at first. This tutorial will go through the process of writing a simple plugin, adding some options, and even perform a callback.


Create a basic jQuery plugin

At the most basic level, you can write a plugin simply by adding a new function property to jQuery’s $.fn object, as follows:

   $.fn.myPluginName = function() {
      // your plugin logic here
   };

This will work great but we need to wrap our plugin logic in an anonymous function. To ensure that our use of the $ sign as a shorthand creates no conflicts between jQuery and other JavaScript libraries, we simply pass it to this closure, which maps it to the dollar sign, thus ensuring that it can’t be affected by anything outside of its scope of execution like this:

(function( $ ){
   $.fn.myPluginName = function() {
      /* The plugin will be returned for every selector */
      return this.each(function() {
         // your plugin logic here
      });
   }; 
})( jQuery ); 

 Load the plugin

It is good practice that you save your plugin in a separate file and just include it in the calling html file. First, load the last version of jQuery as your plugin will need this to work.

<div id="selector" class=""></div>

<script src="//code.jquery.com/jquery-2.1.4.min.js"></script> 
<script src="path_to/yourPlugin.js"></script> 
<script type="text/javascript"> 
   $( document ).ready(function() { 
      $( '#selector' ).pluginName(); 
   }); 
</script> 

 Best Practices

Let’s incorporate some best practices (including those in the jQuery plugin-authoring guide) to this plugin more suitable for deployment.

  • Common best practices, such as a semi-colon before the function’s invocation; window, document, undefined passed in as arguments; and adherence to the jQuery core style guidelines.
  • A basic defaults object.
  • A simple plugin constructor for logic related to the initial creation and the assignment of the element to work with.
  • Extending the options with defaults.
    A lightweight wrapper around the constructor, which helps to avoid issues such as multiple instantiations.
/* This is a lightweight plugin template to get you started */
;(function ( $, window, document, undefined ) {

    /* Create the defaults once */
    var pluginName = "PluginName";
    var defaults = {
        propertyName: "value"
    };

    /* The actual plugin constructor */
    function Plugin( element, options ) {
        this.element = element;

        this.options = $.extend( {}, defaults, options) ;
        
        this._defaults = defaults;
        this._name = pluginName;
        
        this.init();
    }

    Plugin.prototype = {
        
        init: function() {
            console.log("Initialization");
        },

        method1: function() {
            response = "method1 no args";
        },
        
        method2: function(args) {
            response = "method2. Args = "+args;
        }

    }

    /* A really lightweight plugin wrapper around the constructor, 
     * preventing against multiple instantiations */
    $.fn[pluginName] = function ( options ) {

        response = null;

        // slice arguments to leave only arguments after function name
        var args = Array.prototype.slice.call(arguments, 1);        
        
        this.each(function () {
        
            if (!$.data(this, 'plugin_' + pluginName)) {
        
                if(typeof options === 'string') {

                    // get selected operation/method
                    var operation = Plugin.prototype[options];
                    
                    if (operation) {
                        operation.apply(this, args);
                    }else{
                        console.error('Unknow operation: \'' + options + '\'');    
                    }

                } else {
                    $.data(this, 'plugin_' + pluginName, new Plugin( this, options ));
                }
        
            }
        
        });

        return response;
        
    }

    window.Plugin = pluginName;

})( jQuery, window, document );

There are a lot of jQuery plugins available online now. Before starting to create your own plugin, check whether a plugin with the same functionality already exists by visiting the jQuery plugin registry. You can access all the source code in this article (well documented) with a demo from the github link below.

Source Code