What Will I Learn?
In this tutorial, we take a look at how to create jQuery plugins.
Difficulty
- Intermediate
Tutorial Contents
- How to create jQuery plugins
-Naming jQuery plugin files
-Methods and functions
-Packaging complex parameters - Time to create a simple plugin
-Step 1: Set up the template
-Step 2: A dummy test
-Step 3: Wrap up parameters
-Step 4: Define the actual mechanism
-Step 5: Test it one more time
How to create jQuery plugins
The indisputable quick rise of jQuery among a large school of JavaScript libraries relies on a few factors:
- A light-weight core library, its ability to "write less, do more";
- Strong community support;
- Sizable and fast-growing repertoire of plug-ins.
In this tutorial, we take a look at how to create jQuery plugin. Before we dive into details, let’s look at some of the general guidelines for writing jQuery plugins.
Naming jQuery plugin files
Generally we name the plug in file in the following fashion:
jQuery.plugin.js
That is, prefix the file name with jQuery, conclude it with .js extension, and put the real plugin name in the middle, so a watermark jQuery plugin will have the following file name: jQuery.watermark.js
Methods and functions
In jQuery, there are two different types of plugins: methods and functions. Methods directly operate on DOM elements and are attached to the jQuery.fn object. For example,
1. A dummy jQuery plugin
jQuery.fn.changecolor = function(color) {
return this.each(
function() {
$(this).css('backgroundColor', color);
return false;
});
};
On the other hand, functions are utilities that operate not on DOM elements, but on strings, numbers and other data types. They are attached to jQuery object. For example, the following is a dummy function to change all numbers to percentages:
2. A dummy jQuery function
jQuery.percentageformat = function(number) {
return (number * 100) + '%' ;
};
From the above two dummy plugins, we can also see some other general principles
- 'this' is a reference to the current jQuery object.
- Any methods or functions you attach must have a semicolon (;) at the end
- methods must return the jQuery object, unless explicitly noted otherwise.
- Use this.each to iterate over the current set of matched elements
Packaging complex parameters
We all have seen functions / methods with interminable list of parameters. Even worse, users are forced to supply values for those parameters when they are clueless about. In jQuery, the way to avoid this is to use the $.extend() function, and set all parameters as optional while setting their default values. As in the following code:
3. jQuery extend function to make parameters manageable
jQuery.fn.watermark = function(url, options) {
// define defaults and override with options, if available
// by extending the default settings, we don't modify the argument
settings = jQuery.extend({
name: "defaultName",
size: 5,
global: true
}, options);
Time to create a simple plugin
The web is a never-ending stream of inflow and outflow of data. Forms of textboxes, radios and checkboxes play a major role. Sometimes we get tired of the boring little square checkboxes, so we want to give them a little make-up. How about using different images for checked and unchecked?
So let’s do it.
Step 1: Set up the template
The first thing is set up an empty shell. Let us create a file named jQuery.prettycheckbox.js, and put the following code in it:
4. An empty jQuery plugin shell
jQuery.fn.prettycheckbox = function(options) {
return this.each(
function() {
return false;
});
};
Step 2: A dummy test
Now, let’s test it to make sure that this do-nothing plugin would at least work with a web page. So we create a test HTML page, add a reference to the jQuery core library file and to the plugin file we just created.
<script>
$(document).ready(function() {
$('input[type=checkbox]').prettycheckbox();
});
</script>
Step 3: Wrap up parameters
Next, we use the jQuery .extend function to wrap all the necessary parameters in the one umbrella options parameter.
/* Default settings */
var settings = {
imgChecked: 'imageChecked.jpg', /* checkbox */
imgUnchecked: 'uncheck.gif' /* checkbox */
};
/* Processing settings */
settings = $.extend(settings, options || {});
Step 4: Define the actual mechanism
To give the square checkbox a makeup, we set out to do three things:
- Use two images to represent the two states of a checkbox, checked or unchecked;
- Write event handlers for the images’ mouse click events;
- Hide the actual checkbox, and change its state upon the mouse click event.
Simple enough, right? And we implement it as the following
5. Inside the pretty Checkbox plugin
/* Wrapping all passed elements */
return this.each(function() {
var ch = this;
/* Creating wrapper for each checkbox, also i */
ch.wrapper = $('
+ settings.imgUnchecked
+ '" />');
ch.image = ch.wrapper.children('img');
/*mouse click event handling toggle check / uncheck image*/
ch.wrapper.click(
function() {
if (ch.image.attr("src") == settings.imgChecked)
ch.image.attr("src", settings.imgUnchecked);
else
ch.image.attr("src", settings.imgChecked);
//update the checkbox state upon mouse click
ch.checked = !ch.checked;
}
);
//hide the checkbox
$(ch).css({ position: 'absolute', zIndex: -1, display: 'none'
}).after(ch.wrapper);
});
Step 5: Test it one more time
Now we can test our plugin to see it in action. The following test also iterates through every checkbox to make sure it is checked / unchecked correctly.
6. Put the checkbox plugin in use
<script>
$(document).ready(function() {
$('input[type=checkbox]').prettycheckbox();
// add click event to the button
$('#button1').click(
function() {
//test each checkbox
getCheckBoxValue();
}
);
});
function getCheckBoxValue() {
// Loop over each customized checkbox.
$('input[type=checkbox]').each(
// The "indIndex" is the
// loop iteration index on the current element.
function(intIndex) {
alert("checkbox " + intIndex + " checked: " + this.checked );
}
);
}
</script>
Screenshot of the pretty checkbox plugin at work
With so much said and done, the craze for jQuery is still on-going and will be likely for a very long time. The power of jQuery lies as much in its core library as its mushrooming plugins. The jQuery plugin reportoire is an inexhautable magical tool box. In this article we go on a brief tour on a: how to create a plugin ourselves, especially, how to create a nifty customizable checkbox; b. the officially-designated gems of jQuery ui library dealing with mouse interactions. Needless to say, the author has borrowed a great deal from what other people have said and coded before, and sometimes may have even forgotten the source of benefactors. If that happens, thanks and sorry.
Happy jQuery plugging in!
Posted on Utopian.io - Rewarding Open Source Contributors