JQuery Plugin

How to Write Your Own JQuery Plugin?

If you are JavaScript Developer, you probably know jQuery. But do you know how to use it to create your own JQuery Plugin? Read on to get started!

For those who don’t know, JQuery is a JavaScript library that comprises of a number of features, and is quite small yet fast. It also comprises of an easy-to-use API that is compatible on all browsers and enables easier HTML traversal, animation, DOM manipulation, and event handling. It is not only extensible but durable. Hence, client-side scripting has become a lot easier since its development.

What Are JQuery Plugins?

JQuery consists of prototype objects which may require some manipulation and extension. For the same purpose, JQuery plugins were devised as a way for objects to inherit any additional methods that are added. Not only that, these additional methods are not isolated but called with the rest of the methods (already inherited) when the JQuery object is created. JQuery plugins are available individually in the form of individual methods that exist in the JQuery library. Every method is a plugin. But, in case of something new, the plugin can also be custom created, which is not very difficult a task.

How Does JQuery Work?

To understand how JQuery works, you need to follow these steps:

  • Create an HTML document with all the basic tags and calling the JQuery.js file.
  • Developers think ahead and encapsulate the executable commands of the code into an onload() function in order to ensure that the commands execute as soon as the document is loaded into the browser.
  • At times, due to the delay in the loading of images, the document is not loaded in its entirety.  To ensure that the complete document is ready to be worked on after loading, developers supply a ready event into their code.
  • The complete script for the ready event, with the function encapsulated in it, is put inside the HTML document created earlier. Saving and running the document will ensure that your code executes with an output.
  • This function could contain any event (sub-events) or commands to perform a certain task.

What Is the Basic Plugin Signature?

$.fn.pluginName = function() {
this.css( "color", "yellow" );
 }; 
$( "a" ).pluginName();

The plugin starts its identity creation as shown above. pluginName is replaced by the name of your plugin that is being created, followed by a function and any required parameters in the brackets. Further on, the next statement inside the function (this.css) is ensuring that the CSS is applied to certain text to make it yellow in color. The last line calls the plugin function to turn all the links with ‘a’ tag yellow.

Protecting the $Alias and Adding Scope

A jQuery plugin is always written with an assumption that using $  is using an alias of jQuery function. $ is quite famous among JavaScript libraries. So, when more than one jQuery library is required, a conflict may arise with the use of  $. Therefore, to enable us to use jQuery with other plugins along with $, we must place the code inside the expression of the immediately invoked function. This is followed by the passing of jQuery and then naming its parameter $.

Adding Private Methods and Variables

In JavaScript, functions contain several variables and other functions that can be mainly accessed inside the function thereby making the elements private. Immediately invoked function efxpressions provide the best way to access private variables and methods.

Adding private methods or variables can be understood here after the alias ($) matter is resolved:

(function($) {
  $.fn.pluginName = function() {
   // private variables
   var privatevar1 = '';
   var privatevar2 = '';
   // private methods
   var myPrivateMethod = function() {
    // do something ...
   }
})(jQuery);

Adding a private variable and enabling its use is only possible through the Immediately Invoked Function:

(function($){
  var col = “yellow”;$.fn.pluginName = function() {
  this.css("color", col);
  return this;
  };
}(jQuery));

Private methods can only be called from within the scope of the function. Only other private methods or public methods have the authority to call these private methods. This also goes for accessing the private variables.

Adding Public Methods

Adding methods to jQuery plugins is done as it is done in private methods. The only difference is the execution of the method. When the method is supplied with a ‘this’ operator, the method becomes public. This way it can also be accessed outside the scope of the function. The purpose of adding such public methods could be either to perform a function outside the scope or to access the public variables and methods from outside the scope.

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

Accepting Options for Plugin Customization

There are cases where your plugins start becoming complex, as you continue to add to them. Therefore, it is a good idea to make your plugin start accepting some options and make them customizable.

(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));

Putting it All Together

Combining all methods, the following example plugin is compiled:

(function($) {
    $.fn.pluginName = function(options) {
        var defaults = {
            color: "white",
            'background-color': "#556b2f"
        };
        var settings = $.extend({}, defaults, options);
        if (this.length > 1) {
            this.each(function() { $(this).pluginName(options) });
            return this;
        }
        // private variables
        var privatevar1 = '';
        var privatevar2 = '';
        // private methods
        var myPrivateMethod = function() {
            // do something ...
        }
        // public methods 
        this.initialize = function() {
            // do something ...
            return this;
        };
        this.myPublicMethod = function() {
            // do something ...
        };
        return this.initialize();
    }
})(jQuery);

Here, the method ‘each()’ is used to loop through a collection of elements. Also, the return value for this method is the this.append() method, which accepts the callback where upon its return we will be able to see what element is being appended to in the collection.

Rahul Sharma

Rahul Sharma is a Founder of Logical IDEA and Bee Flirty. He is a Professional WP Developers, UX Designer, and Digital Marketing Expert. Previously, He Worked as a Digital Marketing Head for An eCommerce Startup. He Graduated with honors from Lovely Professional University with a Dual Degree in Information Technology.

124 comments

Leave a Reply

Your email address will not be published. Required fields are marked *