Print Shortlink

jQuery Plugin – II

In my previous post, I discussed creating a simple plugin in jQuery using the “fn” property. Let’s extend it further.
jQuery  provides a method chaining mechanism that makes coding easy. Say, you want to change the color of a text and change its’ value, you can write it as follows,
$(“#id”).text(“newValue”).css(“color”,”red”)
How do you get this facility for our changeColor plugin?
$.fn.changeColor = function(color){
    $(this).css(“color”,color);
    return $(this);
}
Returning the invoked object using $(this) gives the ability to pad up more methods.

If you call changeColor with more than one element like $(“#id1,#id2”).changeColor(“red”) then you can modify the code as below
$.fn.changeColor = function(color){
         return $(this).each(function(){
              $(this).css(“color”,color);
        });

changeColor returns an array of the ‘invoked’ objects.
So our plugin can be chained now as shown below.

$(“#id1,#id2”).changeColor(“red”).text(“Chained”); 

Leave a Reply