How to Create a simple jQuery Plugin



A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. Why should we create plugins? in simple meaning: For re-usability. By extending jQuery, we create reusable components that can be used on any web page. Our code is encapsulated and there is less risk that we will use the same function names elsewhere.

How jQuery works:
First we will understand a little about how jQuery works. Take a look at below code:

// color all <div> tags blue
$("div").css("color", "blue");

Note: The jQuery library is named ‘jQuery’, ‘$’ is a shortcut variable that references it.

Whenever we use the $ function to select elements, it returns a jQuery object, which is an array-like collection of DOM elements. This object contains all of the methods we have been using (.css(), .click() etc.) and all of the DOM elements that fit the selector (in our example code shown above, all divs). The jQuery object gets these methods from the $.fn object. This object contains all of the jQuery object methods, and if we want to write our own methods, it will need to contain those as well.

How Plugin works:

jQuery allows methods to be added to its library. When called, these methods are passed the jQuery object within the JavaScript ‘this’ object. The DOM elements can be manipulated as required and the method should return ‘this’ so other functions can be chained.

Plugin Declaration:

Plugins are defined using the jQuery fn function, e.g.
$.fn.subText = function(params) { ... };


Parameters:

We require two parameters for our plugin: minlength and maxlength. It is easiest to define these as function arguments, e.g.

$.fn.subText = function(startFrom, length) { ... };

// example
$("p").subText(5, 15);


The first line in our subText function should define a set of default parameters which would be overwrite with any user-defined values. The jQuery extend function can handle this for us:

// merge default and user parameters
var defaultValue = {startFrom:0, length:10};
var params = $.extend(defaultValue , params);


Our Plugin Code:

$.fn.subText = function(params) {
            // merge default and user parameters
            var defaultValue = {startFrom:0, length:10};
            var params = $.extend(defaultValue , params);
            // traverse all nodes
            this.each(function() {
                        // express a single node as a jQuery object
                        var $t = $(this);
                        // find text
                        var oText = $t.text();
                        // text length within given limits?
                        if (oText.length >= params.startFrom &&  o.length <= params.length)
                                     $t.text(oText.subString(params.startFrom,params.length);              

                // allow jQuery chaining
                        return this;


       });
                       

Note: To make the plugin method chainable takes one line of code:


// allow jQuery chaining
return this;


In the last step, we should make our plugin protect and adding scope. To do this, we should wrap our code up in the below block.

(function($){

} (jQuery));


Like this:

(function($){

$.fn.subText = function(params) {
            // merge default and user parameters
             var defaultValue = {startFrom:0, length:10};
             var params = $.extend(defaultValue , params);
            // traverse all nodes
            this.each(function() {
                        // express a single node as a jQuery object
                        var $t = $(this);
                        // find text
                        var oText = $t.text();
                        // text length within given limits?
                        if (oText.length >= params.startFrom &&  o.length <= params.length)
                                     $t.text(oText.subString(params.startFrom,params.length);              

                 // allow jQuery chaining
                        return this;

       });

} (jQuery));





           

Comments

Popular posts from this blog

Data Bound Controls in ASP.Net - Part 4 (FormView and DetailsView controls)

ASP.net: HttpHandlers

The Clickjacking attack and X-Frame-Options