JQuery is all the rage these days. I’ve been using it a little bit over the past few months, and have been studying example usage of it on the side. One thing you always hear about is how simple the plugin architecture is. So, I decided to test it out, and came up with “The most basic JQuery plugin ever” (imagine music as emphasis in the background….):
Plugin (drop this in its own JS file, or within a <script type=”text/JavaScript”/> block on your page:
Example usage:// The “backgroundColorizer” plugin allows you to essentially
// color alternative odd/even rows’ background(thrilling, eh?)
(function ($) {
$.fn.extend(
{
backgroundColorizer: function (options) {
var defaults = { oddColor: ‘red’, evenColor: ‘blue’ };
var options = $.extend(defaults, options);
return $(this).each(function (index) {
var obj = $(this);
if (index % 2 > 0) {
obj.css(“background-color”, options.oddColor);
} else {
obj.css(“background-color”, options.evenColor);
}
});
}
});
})(jQuery);
(put this html in a blank html/aspx/php, whatever page):
<ul> <li>one</li> <li>two</li> <li>three</li> <li>four</li> </ul> <table> <tr><td>Jane </td><td>Smith</td></tr> <tr><td>Joe </td><td>Smith</td></tr> <tr><td>John </td><td>Doe</td></tr> <tr><td>Jane Q. </td><td>Public</td></tr> </table>
…and here are two JQuery selectors using the plugin:
(function () { $('ul li').backgroundColorizer(); })(jQuery); $().ready(function () { $('table tr').backgroundColorizer({ oddColor: 'green', evenColor: 'lightgreen' }); });
And there you have it kids; THE MOST BASIC JQUERY PLUGIN EVER!!!!!!!!!!!!!!!!!!!!!!!!!……
Pingback: jQuery plugin – “backgroundColorizer” – declarative approach « Jason Harper’s blog