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

One of the reasons jQuery is so popular is the number and quality of its' plugins. They allow quickly achieve user goals and get on with their lifes. A lot of tasks can be done by jQuery plugins without ever have to write any custom jQuery code.

However, when you write some awesome code and think the community will benefit from it - release it as jQuery plugin. In this post, you will learn how to extend jQuery with your custom plugins.

Extending jQuery is quite easy. All you have to do is to use the following template:

(function($){
  $.fn.extend({

    your_plugin_name: function() {
      // Your plugin code
    },

    another_method: function()}{
      // Another method code
    }

  });
})(jQuery);

Your custom plugins will then be available like so:

$('.selector').your_plugin_name();
$('.another-selector').another_method();

Functions will be called once for each element selected by the selector. this would refer to the current element.

Let's say we want a plugin that binds a click event.

(function($){ 
  $.fn.extend({ 
    clickable: function() { 
      return $(this).bind('click', function(){ 
        alert('Custom plugin click!'); 
      });
    }
  }); 
})(jQuery);

$('#clickatron a').clickable();

jQuery uses method chaining pattern. So if you want your plugin to be cahinable, you need to return jQuery object from your newly created methods like we did in the previous example. Because, .bind() returns a jQuery object, we can chain another jQuery methods to it. Here is an example.

$('#clickatron a').clickable().addClass('clickable');

One more method to extend jQuery object with your custom functions is to define methods right on the $.fn object. I personaly prefer $.fn.extent() syntax because it makes code more readable and hints you that we are indeed extending jQuery. Here is an alternative method.

(function($){
  $.fn.your_plugin_name: function() {
      // Your plugin code
  };

  $.fn.another_method: function() {
      // Another method code
  };
})(jQuery);

NOTE
Technically the two methods are the same. They both "extend" $.fn object by defining new properties on it.