Techumber
Home Blog Work

Create Your Own JQuery Plugin

Published on August 28, 2012

Hi friends, Today I will teach you how to create your own jquery plugin with simple code example. JQuery is most amazing client side scripting tool. Basically jquery is a JavaScript library. By using it we can write client side scripts very easily. But sometimes the existing features of JQuery won’t be enough. So we need to create our own jquery plugin. Just follow the steps to create your own plug-in. We will create a plug-in called extAlert.js in this same tutorial. You can download the Code Examples from below link, also check out the demo. Create Your Own JQuery Plugin

Demo

Download

Output Screen shot

Create Your Own JQuery Plugin

What this plug-in do?

This plug-in do two things.

  1. Highlight the all external links.
  2. Asks for confirmation when you click on the external links. First of all create the folder structure as below.

Step 1

(function($){
$.fn.YourPluginName=function(){
// plug-in code goes here...
........
........
};
})(jQuery);

In above code YourPluginName will be the name you want to give to your plug-in. Later will we have to use same name to call our plug in along with selector. In general name should tell what does that plug in do. In our case we will name it as extAlert.

Preventing Library conflicts

(function($){
.........
.........
})(jQuery);

$ sign is used by many other major client libraries. So in order to prevent the conflicts it is always suggested write your code inside it. Here $ will be replaced with JQuery This two lines of code will help your to write short code. For example in our plug-in we write as $.fn.YourPluginName=function() if we write the code in side above code otherwise we should write it as jQuery.fn.YourPluginName=function(). It is not a new thing most of the JavaScript coders use this technique. If you are not from JavaScript background. The above code is self calling function where we send jQuery as parameter. It is not mandatory to use only $ We can use any symbol we want for example, You can use @ in above code. Then we write our plug-in code as @.fn.YourPluginName=function(). Cool right! Ok now come back to our plug-in.

Step 2

(function($){
$.fn.YourPluginName=function(){
return this.each(function(){
...........
...........
});
};
})(jQuery);

Here we need to understand two thinks. First we returning this object so that the plug in support chainability. chainability means you can do as many plug-in function call you want like $(selector).plugin1().plugin2(); Second thing is we are looping each of this object. Here this object is the selector. Most of the time be we want to apply our plug-in to all matched selectors. In your example we will use $(‘a’).extAlert(); Here a single page may have more than one anchor tag.

Step 3

(function($){
$.fn.YourPluginName=function(options){
return this.each(function(){
var o=$.extend({
prop1:val1,
prop2:val2,
//so on...
..........
},options);
// Plug in code
..........
..........
});
};
})(jQuery);

We use JQuery extend method to overwrite default properties of plug-in to user given properties. Until now is a very basic structure to create JQuery plug-in. Now let’s see how we create our JQuery plug-in extAlert.

extAlert.js

(function($) {
  //Your Plug in code stars here
  $.fn.extAlert = function(options) {
    //Returning this object so that it can maintain chain ability
    return this.each(function() {
      //extending the default parameter with user parameters
      var o = $.extend(
        {
          lc: true, //Enable/disable background colour to external link
          lcv: '#9fc', //link colour if you want set the link colour
          lfs: 'italic', //link font style you specify the font style default is italic for external links
        },
        options,
      );
      // collecting domain name, all href values.
      var host = window.location.href.split('/')[2].toLowerCase();
      var ahref = $(this).attr('href');
      var a = ahref.split('/')[2].toLowerCase();
      //checking wether href val match with domain name
      if (host != a) {
        if (o.lc) {
          $(this).css('background-color', o.lcv);
        }
        $(this).css('font-style', o.lfs);
      }
      //Click event on a tags.
      $(this).click(function(e) {
        e.preventDefault(); //Preventing default click event
        // if link is from other domain it will ask confirmation.
        if (host != a) {
          var cnf = confirm('Press OK to go! ');
          // If user want to go new domain location
          if (cnf) {
            window.location.href = ahref;
          }
        }
      });
    });
  };
})(jQuery);

Conclusion

This is only for absolute beginner who want to write their first JQuery plug-in. we can create much more complex plug-in using different JavaScript design patterns. That’s it hope you like it.