jQuery - Chaining
In general terms, An associated adaptable arrangement of metal connections utilized for affixing or securing items and pulling or supporting burdens is known as chaining.
In Jquery, Chaining means to connect multiple functions, events on selectors. Chaining permits us to run different jQuery methods (on the same element) inside a single statement. You can easily understand the concept of chaining through following sample codes :-
Sample code 1: Without Chaining
The main problem with this code is that for every statement, jQuery search for entire DOM and find the element and after that executes the attached function on it.
$(document).ready(function(){
$('#dvContent').addClass('dummy');
$('#dvContent').css('color', 'red');
$('#dvContent').fadeIn('slow');
});
Sample code 2: Using Chaining
In this Sample code, jQuery finds the element only once and execute all the attached functions one by one. This is the advantage of Chaining.
$(document).ready(function(){
$('#dvContent').addClass('dummy')
.css('color', 'red')
.fadeIn('slow');
});
Some important points to remember :-
1. It makes your code short and easy to manage.
2. It gives better performance.
3. The chain starts from left to right. So left most will be called first and so on.
4. Chaining also works with events in jQuery
For example :-
$(document).ready(function() {
$("#btnDummy").click(function(e) {
alert("click!");
}).mouseover(function(e) {
alert("mouse over!")
}).mouseout(function(e) {
alert("mouse out!")
});
});
In the above example, two events are used : mouseover and mouseout
0 Comment(s)