Monday, December 15, 2008

How to create a jQuery plugin, extending jQuery the easy way

I have read a great book on jQuery Learning JQuery. I skimmed through the chapter on extending jQuery and creating its plugins. It is quite easy. All you have to do is to use this template:

(function($){ 
    $.fn.extend({ 
        myFunk: function() { 
            // You must return jQuery object 
            return $(); 
        }, 
        myPunk: function() { 
            return this.addClass('punked') 
                      .bind('click', function(){ 
                alert('You were punked!'); 
            }); 
        } 
    }); 
})(jQuery);

Then you can use your defined functions like this:

$('.select').myFunk(); 
$('.select').myPunk();

jQuery uses method chaining pattern so you need to return jQuery object from your newly created methods.


2 comments:

Zoramite said...

FYI, the myPunk function should say return instead of retun.

Uzbekjon said...

Thanks Zoramite. I corrected the typo...

Post a Comment