jQuery Plugin – How to’s

jQuery plugin
Spread the love

A plug-in is a software component that can be added as an element of our software program to provide support for specific features or functionality, without affecting the source program in any manner. It is an independent module that enables customization to an application. A jQuery plugin is a method that we use to extend jQuery’s prototype object. It is a piece of code written in a JavaScript file, which enables all jQuery objects to inherit any methods that you add. Before getting more into jQuery plug-ins, we need to know what jQuery is.

jQuery is a JavaScript library that allows web developers to add extra functionality to their websites. It simplifies and standardizes interactions between JavaScript code and HTML elements. It is open source and most extendable. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code. jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation. jQuery is adapting the ‘write less, do more’ concept; it can be used to make code simple, concise and reusable. It simplifies the process of traversal of the HTML DOM tree and also handles events, performs animation and adds ajax support in web applications.

jQuery utilizes a combination of CSS, AJAX, JavaScript, and HTML. These markup-based technologies have been designed to work perfectly together.  jQuery uses a clean, simple, and powerful syntax that makes it easy to select the DOM elements on the website page. It provides lots of utility functions that assist in coding string iteration, array manipulation, trimming, and other features. These functions help in providing seamless assimilation between jQuery and JavaScript. jQuery elements will still render even when JavaScript is disabled. This means that you can still display your animations while being SEO-friendly (search engines can crawl each page on the website efficiently, interpret the content effectively, and index it in their database). Furthermore, the faster loading pages of jQuery will help to boost your website rankings even further.

To implement jQuery, a web developer simply needs to add the reference of the jQuery JavaScript file within thesection of the HTML of a webpage. We can do this in two ways; either you can include jQuery library from a CDN (Content Delivery Network) to host yourself, 

Or place the downloaded file of jQuery library in the same directory as the pages where you wish to use it and add reference inside

We must first understand a little about how jQuery works. Take a look at the following code and see what’s happening behind the scenes:

$(“a”).css(“color", "red" );

Whenever you use the $() function (also known as wrapper function) to select a group of elements in DOM, it returns a jQuery object. This object contains all of the jQuery methods (.css(), .click(), etc.) and all of the elements that fit your selector (here selector is “a”). This jQuery object is a wrapped set, an array-like structure that contains all the selected DOM elements. You can iterate over this wrapped set like an array or access individual elements via indexer. The jQuery object gets these methods from the $.fn object. This object contains all of the jQuery object methods, and if we want to write our own methods, it will need to contain those as well. 

How to create a jQuery plug-in?

The idea of a plugin is to do something with a collection of elements. For example, you want a single method so that you can call on a jQuery selection which performs a series of operations on the selection. In this case, you may want to write a plugin. These files provide useful jQuery methods which can be used along with jQuery library methods. 

To make a plug-in's methods available to us, we include a plug-in file very similar to jQuery library file in theof the HTML document. We must ensure that it appears after the main jQuery source file, and before our custom JavaScript code. If our plugin file is debug.js, we have to include that in HTML like this:

The jQuery method which we are creating for our application to customize acts as the plugin. You can define variables and methods (both can be private or public) inside the plugin. Following is the syntax for creating a method inside the plug-in file:

$.fn.methodName = function(){

//method definition

};

The points to be noted while creating a method are:

  • Any methods or functions you attach must have a semicolon (;) at the end.
  • Always add a plugin to jQuery’s namespace with $.fn
  • Your method must return the jQuery object, or it should be explicitly noted.
  • You should use ‘this.each()’ to iterate over the current set of matched elements.
  • You should use the $.noop function instead of empty functions inside plugins. 

Let’s go through the above example, to change the text colour to red, how to implement that using a plugin. Write the following method in the file debug.js

$.fn.makeitred = function() {

    this.css (“color", "red”);

    return this;//not required, but highly recommended

};

And in HTML, use the plug in as follows insidetag:

This will change the content inside the

tag of the HTMLpart into red colour. We can use this plugin, wherever you want in the HTML.

Different features of jQuery Plugins

Now let’s have a look at some features of jQuery plugins and some important points to be noticed, with examples.

  1. We can implement chaining (call another function or plugin on the same returned results in one line of code), as follows:

$(“p”).makeitred().addClass( "active" ); 

  1. To work well with other plugins, and still use the jQuery $ alias, we need to put all of our code inside of an Immediately Invoked Function Expression, and then pass the function jQuery, and name the parameter $, like:

(function ( $ ) {

    $.fn.makeitred = function() {

        this.css( "color", "red" );

        return this;

    };

}( jQuery ));

We can declare private variables also to hide our custom colour, which enables encapsulation.

  1. It's good practice when writing plugins to only take up one slot within $.fn and use parameters to control what action that one slot performs. This will help in minimizing plugin footprint. 

(function( $ ) {

    $.fn.changecolor = function( action ) {

        if ( action === "active") {

        this.css( "color", "red" );

        }

        if ( action === "inactive" ) {

        this.css( "color", "blue" );

        }

  return this;

    };

}( jQuery ));

  1. A typical jQuery object will contain references to any number of DOM elements, and that's why jQuery objects are often referred to as collections. If you want to do any manipulation with specific elements (e.g. getting a data attribute, calculating specific positions) then you need to use ‘.each()’ to loop through the elements. Notice that we return the results of .each() instead of returning this. Since .each() is already chainable, it returns this, which we then return.

(function( $ ) {

    $.fn.makeitred = function() {

        this.filter( "a" ).each(function() {

            this.css( "color", "red" );

        });

        return this;

    };

}( jQuery ));

This plugin will go through all the DOM elements and change the color of the contents of all tag into the red.

  1. If you are not sure about the functionality or requirements, we will define empty functions in the initial stage of coding. jQuery provides the $.noop function instead of empty functions. This does the same thing but avoids the overhead of creating multiple anonymous functions. For example, 

options = $.extend({

  // ...,

  onItemClick: function(){},

  onItemOpen: function(){},

  onItemClose: function(){}

}, options);

Instead of these empty functions, you should define like this:

options = $.extend({

    // ...,

    onItemClick: $.noop,

    onItemOpen: $.noop,

    onItemClose: $.noop

}, options);

  1. Plugins can be passed a series of options to change the way they work. These options are passed to your function in the HTML as a series of key/value pairs (a JavaScript object), like this:

$( "div" ).makeitred({

    color: "orange"

});

To give our plugin the ability to process options we need to define the default settings to be used. We can then use jQuery’s ‘$.extend()’ method to merge our default options with the options passed in when our plugin is called. Our makeitred() plugin with options can be modified using $.extend() like this:

(function ( $ ) {

    $.fn.makeitred = function( options ) {

        // This is the easiest way to have default options.

        var settings = $.extend({

            // These are the defaults.

            color: “#ff0000”,

            backgroundColor: "white"

        }, options );

       // Make the collection colour based on the settings variable.

        return this.css({

            color: settings.color,

            backgroundColor: settings.backgroundColor

        });

    };

}( jQuery ));

Now when we pass color: "orange" through the plugin in HTML, the default value will be overridden and text colour changes to orange.

  1. Event listeners are callback functions that will be called at a specific moment, will let you hook into key parts of your plugin and trigger additional functionality. You define these callbacks as elements in your default options. The callbacks work by calling your options when they are triggering. The event listener will have access to both the $item and the event and be able to customize your functionality. This can give the developer access to your plugin at crucial times so they can extend or modify it to suit their needs. Following is the example for an animate menu, where mouseover() and mouseout() events are handled in the plugin file animate.js :

(function($){

   $.fn.extend({ 

      animateMenu: function(options) {

         var defaults = {

animatePadding: 60,

            defaultPadding: 10,

  };

  var options = $.extend(defaults, options);

       return this.each(function() {

    var o = options;

    var obj = $(this);

    var items = $("li", obj); 

    items.mouseover(function() {

      $(this).animate({paddingLeft: o.animatePadding}, 300);     }).mouseout(function() { 

      $(this).animate({paddingLeft: o.defaultPadding}, 300);

    });

       });

      }

   });

})(jQuery);

Following code will help the animateMenu() plugin to work:

 

 

 

 

 

    • Home

 

 

    • Posts

 

 

    • About

 

 

    • Contact

 

 

 

 

Why do we need jQuery Plugins?

In short, jQuery is the most popular JavaScript library since it works in all browsers, is very easy to learn and use, and requires much less code to attain the same feature in comparison to other JavaScript libraries. jQuery basic syntax script offers a wide selection of animation effects by default. You can easily choose an animation effect of your choice that would greatly fit your website. Most mobile devices will support animations created in jQuery over those created using Flash since it is a newly developed computer program and comes with better adaptability for mobile versions.

To keep the jQuery library lean and lightweight, most functions have been omitted and others have been moved to the plug-in section. If you require any of these omitted features, you can easily add them to your website as plugins. The lean library keeps the coding at a restricted level and helps save on bandwidth to guarantee faster loading. jQuery has a wide range of plugins which are all over the internet. This abundance of plugins helps developers to create special effects more quickly. 

We prefer jQuery plugins over pure JavaScript implementations, as it prevents function conflicts, automates the extension of functions within the plugin, provides chaining, encapsulation and reusability. These plugins can be used to optimize your jQuery website for SEO, a great way to increase the quality of a web site by making it user-friendly, faster, and easier to navigate. With a strong grasp of what jQuery plugins are, you can leverage them to make your development quicker and easier. Now add a bit of excitement to your website or application with jQuery plugins.

For more information on the topic go to Innovature’s  Full stack Development page.