Extending jQuery – jQuery plugin development
Some introductory words.
jQuery is a very popular JavaScript library and why wouldn’t it be popular, it has made the life of us developers so so easy. Its not just that our lives have become easy, but so has our code-base become more cleaner.
Anyways we are not going to discuss the merits of jQuery, I will have a separate post to discuss that. Right now what I would be discussing is how to write plugins for jQuery.
Two ways of extending jQuery:
There are two kinds of ways that you can extend jQuery. As you probably know that methods are different from functions. Methods can be thought of as instance based, while functions can be thought of as static. Let me clear your minds by using an example:
Example of a method:
$('#myform').hide();
Here hide is an instance method that is attached to the jQuery.fn object.
Example of a function:
$.get('someurl.php');
Here get is a static function that is attached to the jQuery object itself.
Well now that the difference between method and function is out of the way, let’s discuss how to extend jQuery by writing plugins.
Implementing a plugin:
Well I will only be showing the implementation of extending jQuery by adding a new method.
$.fn.resize = function( options ) { // setup default options var config = { width: 640, height: 480 }; if(options) { $.extend( config, options ); } this.each( function( index, element ) { // resize the element proportionally var $element = $( element ); var ratio = Math.min( config.width / $element.width(), config.height / $element.height() ); $element.css( { width : ( $element.width() * ratio ) + 'px', height : ( $element.height() * ratio ) + 'px' } ); }); return this; }
The resize method can be used in following ways:
$('.large_image').resize(); $('.large_image').resize( { width: 400, height: 300 } );
There is not much that the our method is doing, its just resizing dom objects proportionally.
- We are using this.each, so that we can apply our resize method to many objects. For example, lets suppose there are four images with the class ‘.large_image’, then with $(‘.large_image’).resize(); our resize method will resize all four images.
- We are returning this from our resize method. This is so that method chaining can be achieved. For example, we might do $(‘.large_image’).resize().show();
Do you see how easy it is to extend jQuery. So when will you be writing your own jQuery plugin?