Tuesday, February 9, 2010

I was playing around with creating Jquery plugins a while ago.  I wanted to comment on this for others.  It turns out making plugins is rather easy.  Jquery is just the coolest javascript library I have ever seen.  There are a number of good templates online and grabbing a simple template and extending it is the easiest thing to do.  I found this one by Dave Smith and you should also refer to the Official Docs.  The reason I like a simple template to start with like the one Dave has is sometimes the official docs since they have to cover every options do not explain how to get started very well.

One comment on Daves template is that one change should be to make the functions that all functions that are not "get" functions should return a reference to "this" so you can chain function (see example).

So basically here is my (slightly modified template):


(function($)
{
$.fn.plugin = function(options) {
  // Set the options.
  options = $.extend({}, $.fn.plugin.defaults, options);
  // Go through the matched elements and return the jQuery object.
  return this.each(function()
  {
  });
};
// Public defaults.
$.fn.plugin.defaults = {
property: 'value'
};
// Private functions.
function func()
{
return;
};
// Public functions.
$.fn.plugin.func = function()
{
return this;
};
})(jQuery);


Now for an example.  Say we wanted to make a trivial template that sets all elements using this plugins color to red and enables you to change the font color and the background color.  You can take the template above and change it like this:



(function($) {  
$.fn.mycolor = function(options)  {   
// Set the options.   
options = $.extend({}, $.fn.plugin.defaults, options);    

// Go through the matched elements and return the jQuery object.   
return this.each(function()   {
// do something with this. Say we wanted to make it red
this.css("color", options.color);
});  
};
// Public defaults.  
$.fn.mycolor.defaults = { 
color: 'red' 
};
// Public functions.  
$.fn.mycolor.setColor = function(color)  {
this.css("color", color);   
return this;  
}; 

$.fn.mycolor.setBackgroundColor = function()  {
this.css("background-color", color);   
return this;  
};
})(jQuery);



Now you can do this:


$(".color_example").mycolor();


This will make all html elements with the class .color_example change colors to red, then to change their colors later in some other context you can do this:


$(".color_example").setColor("blue").setBackgroundColor("black");

Note that unless setColor returned "this" you would have to do this in two function calls.  This is so stupidly trivial it is not useful but hopefully this helps get the idea of how easy it is to make a plugin and do cool things with it.

No comments:

Post a Comment