If you use jQuery, you've heard of its plug-ins - easily reusable bits of code that you can call on selectors like any other jQuery method. What you may not realize is how easy it is to write your own plug-ins, making code reuse in your projects easier then ever.
01: The Set-Up
In order to create a plug-in, you need an environment that supports one. Create a new folder and inside that folder create two documents:
- colorize-test.html
- colorize.jquery.js
<!DOCTYPE html> <html> <head> <title>My First jQuery Plug-In</title> <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script src="colorize.jquery.js" /> <script> $(document).ready(function() { // The DOM is ready, start coding! }); </script> </head> <body> <p>Pellentesque habitant morbi .... </p> <p>Pellentesque habitant morbi .... </p> <p>Pellentesque habitant morbi .... </p> <p>Pellentesque habitant morbi .... </p> <p>Pellentesque habitant morbi .... </p> </body> </html>
The purpose of our plug-in is going to be to change the color of text when clicked. Not very exciting, but the idea is to learn how to create a plug-in, not to create anything special.
02: Writing the plug-in: Deciding the Interface
When writing a plug-in, it's often best to first decide on how it will be used. In the majority of cases, this means determining the options since almost all plug-ins are used by calling them in a chainable fashion on a selector. Here's how using our plug-in will look:
$('.selector').colorize({ colors : ['#FF0000','#00FF00','#0000FF'] });
If the option isn't set then the plug-in will use the default values we assign inside the code.
03: Plug-In Basics
When you write a plug-in, jQuery has a namespace they provide for you to attach it ($.fn) so our plug-in gets wrapped in code like this:
$.fn.colorize = function(options) { ... }
(function($) { $.fn.colorize = function(options) { // Plug-In Code Here }; })(jQuery);
04: Get The Options
The first thing your plug-in code has to do is handle the passed in options. To do this, you have to set defaults and merge any values the user has set when calling the plug-in. Sounds potentially complex, but it's not.
// Defaults and options var defaults = { colors : ['#FF0000','#00FF00','#0000FF'] }; var opts = $.extend({}, defaults, options);
05: Working on Each Element
It's important to remember that jQuery plug-ins are called on a selector which may return between zero and a LOT of items that match the selector. Within the scope of your colorize function, the special variable 'this' will refer to this jQuery collection. So after we've set up our default, we are going to loop over this collection with the 'each' method.
this.each(function() { // This code is applied to every element defined by the selector // the special variable 'this' is redefined here });
var self = $(this);
06: Store the Original Color
In our plug-in, we have to know what color the item was before we started messing with it. To keep track of this, we're going to create an array with the original color as the 0 index value, combined with the colors set in the options. We're also going to set a value called 'color-index' which indicates which color of the array should be displayed at any time.
self.data('colors', [self.css('color')].concat(opts.colors)); self.data('color-index', 0);
07: Add a Click Handler
Since we want the DOM elements to color when clicked, we need to add a click handler. Here's how we do that:
self.bind('click', function() { var index = self.data('color-index'); var colors = self.data('colors'); if(index < colors.length-1) { self.data('color-index', index+1); } else { self.data('color-index', 0); } self.css('color', colors[self.data('color-index')]); });
08: Finising Up
Here's the complete plug-in code:
(function($) { $.fn.colorize = function(options) { // Defaults and options var defaults = { colors : ['#FF0000','#00FF00','#0000FF'] }; var opts = $.extend({}, defaults, options); this.each(function() { var self = $(this); self.data('colors', [self.css('color')].concat(opts.colors)); self.data('color-index', 0); self.bind('click', function() { var index = self.data('color-index'); var colors = self.data('colors'); if(index < colors.length-1) { self.data('color-index', index+1); } else { self.data('color-index', 0); } self.css('color', colors[self.data('color-index')]); }); }); } })(jQuery);
$('p').colorize();
Of course you'd replace 'p' with whatever selector you'd want. In this case I'm putting it on the paragraph tags for our example.
You can download the completed plug-in and sample HTML page: create-a-plugin.zip
In our next jQuery article, we're going to learn how to create a plug-in to enable dependant selects in HTML forms. When you choose an element in the first select, the choices in the second select are populated based on that choice.