Tutorial: How to Write Your Own jQuery Plugins?
Not long ago, I had mentioned few things to note when authoring jQuery plugins. This post, I am going to put things in more practical way. Whereas, I will show you how to write our own jQuery plugin, step by step. In this tutorial, we are going to create a jQuery plugin that can be used to randomly change text colour. Before getting started, you can try out this demo in action.
It is easy to author a jQuery plugin. I am using jQuery v1.3.2 in this tutorial and of course, you are free to use any other versions instead. For instance, the latest version, v1.4.2.
Note: You are highly encouraged to use recent versions for the sake of stability and performance, as well as new features, etc. Personally, I recommend to use at least v1.3.2 and above.
Step 1: Include the jQuery core library file
First and foremost, you are required to grab a jQuery core library and include it, typically within <header> tag. If you don’t know where to go, you can get a copy of jQuery core library from its official website. Here is how we include the file:
<script type="text/javascript" src="jquery.js"></script>
I have basically renamed the file as ‘jquery.js’ which resides in the same web folder with my web page, which is supposed to be used in this tutorial.
Step 2: Scoping and Avoiding Conflict
Once we included the core library, we can start writing our methods and bundle it as plugin. As I have already mentioned in my previous post, it’s always a good practice to scope the jQuery’s alias object, ‘$’ and avoid any conflict with other libraries. So that, we can use the ‘$’ object when authoring our own methods. To do so, write an anonymous function as follows:
(function($){ //put everything inside this function... })(jQuery);
Step 3: Define a method
Next, we are going to create a method that will be attached to jQuery’s fn object so that we can use our own method together with jQuery core methods, so-called ‘chaining’. Say, we defined a method named as randColour and attached to $.fn object:
(function($){ $.fn.randColour = function(){ return this.each(function(){ //our stuff are putting inside 'each' function... }); }; })(jQuery);
To allow us to chain with jQuery’s core methods, we need to put our stuff in jQuery’s ‘each’ function and return it so that it can be tied with others. Keep in mind that, the ‘this‘ reserved word here refers to jQuery object!
Step 4: Put things together
Once we are done with the plugin ’skeleton’, we can then really start writing our stuff and putting it inside ‘this.each()’ function. This tutorial, we are going to define two functions: ‘returnColour()‘ and ‘applyColour(obj)‘.
i) returnColour() – This function will return a randomized colour in RGB format.
ii) applyColour(obj) – As its name applies, we are passing HTML element object to this function and apply the randomized colour to selected text.
So, the complete code is as follows:
(function($){ $.fn.randColour = function(){ return this.each(function(){ //init applyColour applyColour(this); //apply colour to selected text function applyColour(obj){ var rColour = returnColour(); $(obj).css({"color": rColour}); } //return a randomized colour function returnColour(){ var maxRgb = 256; var rgbVal = new Array(); var rgbTxt = "rgb("; //iterate to get rgb value for( var i = 0; i < 3; i++ ){ rgbVal[i] = Math.floor( Math.random() * maxRgb ); if( i < 2 ){ rgbTxt += rgbVal[i] + ","; }else{ rgbTxt += rgbVal[i] + ")"; } } return rgbTxt; } }); }; })(jQuery);
Perhaps, you have noticed that there was an additional line of code in ‘this.each()’ function:
applyColour(this);
We basically use this line of code to invoke the function and passing an object to it once ‘randColour’ is called. Please be mindful, the this word here is now referring to the current object of HTML element, and NOT jQuery object. To make it clearer, it can be read as ‘apply the colour to this selected HTML element’.
Step 5: Calling Our Defined Method
OK, at this stage, we can call our own method through jQuery ready handler whenever we want! For example:
JavaScript:
$(function(){ $("#hello").randColour(); })
HTML
<h1 id="hello">Hello World!</h1> (To change text colour, please click browser's 'Refresh/Reload' button.)
NOTE: Once you are done with the code, you can save it as separate JS file and name it as, ‘jquery.something.js’. For instance, you may name it as ‘jquery.randcolour.js’ so that it can be included in any web page for reuse purpose.
