Saturday, August 30, 2014

How To Create Your Own JQuery Plugin



1. Introduction

JQuery is very popular library which allows you to manipulate DOM easily. It also has lots of plugins. Creating your own plugin seem a bit hard first. However, it's not that much hard. Let us see how to create a simple JQuery plugin.


2. Problem Statement


By default, when you create hyperlink in html, it has underline and has text with blue color. Let us try to convert all hyperlink elements to red color without underline. With basic JQuery you can do like this :


$('a').css('text-decoration','underline')  
$('a').css('color','blue')
Let us create our own JQuery plugin to do above task.


3.  JQuery plugin structure :

(function($){

        $.fn.myFunction = function(){

        }

}(JQuery))


Let's take a quick look to understand above code template. We are defining here anonymous Javascript function i.e. function without name. We are also calling this anonymous function right there with only one parameter i.e. JQuery. By including our functionality in this self-enclosed anonymous function, we are eradicating chances of collision with other Javascript variables/functions.

With $.fn you can define your own JQuery plugin which will be accessible with $ variable later.


4. Simple plugin definition :


Let us define our own convertToMyLink function.


(function($){

       $.fn.convertToMyLink = function(){

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

               this.css('text-decoration','none');         

       }

}(JQuery))



With this, now you can call your own function like as follows :

$('a').convertToMyLink();


5. Chaining :

Most of the JQuery plugins support chaining of functions. For example, $('a').css('color','red').text();

With our current definition chaining won't work. To support that just update the function definition like this :

(function($){

       $.fn.convertToMyLink = function(){

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

               this.css('text-decoration','none');

               return this;         

       }

}(JQuery)) 



6. Accepting options for your function :

Let us provide text color & background color as a option to our function. If color is not provided we will use default one.


(function($){

       $.fn.convertToMyLink = function(userOptions){

       // If userOptions are not provided use following default ones

       var options = $.extend({

                color : 'red',

                backgroundColor : 'white'

       }, userOptions);       



       return this.css({

               color : options.color,

               backgroundColor : options.backgroundColor

       });

}(JQuery))




Example usage :

$("a").convertToMyLink({color : 'green'});
Custom JQuery plugins are very good option when you want to convert you repetitive task into one module. 
Thanks for reading.

No comments:

Post a Comment