Wednesday 31 October 2012

How to Write a jQuery Plugin

It is actually pretty simple, you just have to follow a basic template. Here I am showing you how to build one to change elements to a round shape. Please note that because I use border radius here in the example you need IE9+ to view the result.

(function ($) {
    //This is where you define your plugin name, in this case - makeMeRound
    $.fn.makeMeRound = function (options) {

        //Extend default settings with options passed through paramete
        var settings = $.extend({
            //Below are default settings, can be overridden by parameter
            'border_color': 'red',
            'border_width': '2px'
        }, options);

        //Wrapped in a each loop in case jQuery selector returns a collection of elements
        //We return this here to maintain chainability during method calls
        return this.each(function () {
            //Below is the core of the plugin
            var max = $(this).width() > $(this).height() ? $(this).width() : $(this).height();
            $(this).css('width', max).css('height', max).css('border-color', settings.border_color).css('border-width', settings.border_width).css('border-radius', '50% 50% 50% 50%');
        });

    };

})(jQuery); //To make sure that your plugin doesn't collide with other libraries that might use the dollar sign
 
//Calling plugin
$(document).ready(function () {
    $('input').makeMeRound(); //use default setting
    $('img').makeMeRound({ 'border_width': '2px' }); //specify custom setting
});

The above script operating on the html below

<input type="button" value="Click Me" style="border-width:1px;width:100px;height:25px;"/>
<img border="1px" src="http://www.tutordoctor.com/sites/default/files/Halloween.jpg" />

will produce the following result
 
 

No comments:

Post a Comment