Nov 16, 2009

How to write your own jQuery plugins

Packing your code into plugins will make it easier for maintenance and reuse. JQuery plugins can accelerate the development process and simplify the final product. Writing your own plugins isn’t hard either.

Ok, let’s start with a very simple plugin. I have very little imagination, so my plugin will do very stupid work – it will change the font size and weight of an element. I’ll call it … demoPlugin. Original, isn’t it?

Let’s define it:
$.fn.demoPlugin = function(settings) {
}
And we will call it this way:
$("div").demoPlugin();
Some initial configuration like this:
var config = {'fontSize' : '30px', 'fontWeight' : 'bolder'};
And we will extend it with the parameters provided by the user.
if (settings) 
 $.extend(config, settings);
And our main code goes here:
this.each(function() {
   $(this).css({

      'font-size':config.fontSize, 
      'font-weight':config.fontWeight});
       });
Here is the full plugin code:
(function($) { 
 $.fn.demoPlugin = function(settings) {

   var config = {
    'fontSize' : '30px', 
    'fontWeight' : 'bolder'};

       if (settings) 
    $.extend(config, settings);
 
       this.each(function() {
   $(this).css({

      'font-size':config.fontSize, 
      'font-weight':config.fontWeight});
       });
 
       return this;

  };
})(jQuery);


Don't forget to return this at the end. It is very important in order to use chain calls.

I’ll continue with less trivial plugin example later.

Next plugin article.

No comments:

Popular Posts