Facebook
Banner
XMPP JavaScript Library READ MORE

How to create JQuery like chain functions in JavaScript

JavaScript, Sachin Puri, 2012-10-27 14:58:59

Imagine if we want to call multiple functions in relation of same object.

For example if we want to apply following properties on a DIV with id "div1":

  • change background to #666666
  • change padding to 5px
  • insert "Hello World" in that div

and we have following function to apply these properties

 

function css(element,property,value){

}

function html(element,value){
}

 

then we have to do some thing like this

var ele=document.getElementById('div1')

css(ele,'background','#666666');

css(ele,'padding','5px');

html(ele,'Hellow World')

 

This is how JQuery deals with this situation,

Jquery make use of chain function to call multiple function on a same object

$('#div1').css('background','#666666').css('padding','5px').html('Hello World');

 

This is same implementation in core JavaScript

        var ele=0;

        function $(id){
            ele=document.getElementById(id);
            return this;
        }

        function css(prop,value){
            ele.style[prop]=value;
            return this;
        }

        function html(value){
            ele.innerHTML=value;
        }

        $('div1').css('background','#666666').css('padding','5px').html('Hello World');


 

Where to use Chain Function

Chain functions can be used in situations where we want to apply different functions on a signle or collection of objects. Chain function calls different function in relation of same object one by one thus manuplating the property of that object.

Add Your Comment
   
    Yes! I want to receive all comments by email

No Comments Posted Yet. Be the first one to post comment