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.