By now, you should be pretty familiar with the concept of chaining in jQuery. Chaining allows you to add multiple methods to the same statement. This helps to keep your amount of code smaller and increases the performance of your scripts. In the following example, I use chaining to illustrate how you can add multiple methods to a selector statement. The tooltip is first set to hidden, and then the element is faded in at a speed of 900 milliseconds. A one-second delay occurs, and then it fades out at a rate of 900 milliseconds.
$('.tooltip').hide().fadeIn(9000).delay(1000).fadeOut(9000);
If you were to write that same statement without chaining, it would require three separate statements on three individual lines:
$('.tool-tip').fadeIn(900);
$('.tool-tip').delay(10000);
$('.tool-tip').fadeOut(900);
The preceding sequence of jQuery statements results in the same output as the chained example, but chaining saves space and keeps your code cleaner. Consider a scenario where you need to select three different li elements using their respective ID names and style each of them differently:
<ul id="news">
<li id="politics">Politics</li>
<li id="sports">Sports</li>
<li id="finance">Finance</li>
<li id="world">World</li>
<li id="local">Local</li>
</ul>
You can do this in one of two ways. The first is by creating three statements that each select the element and apply CSS to it:
$('#politics').css('border','1px solid blue');
$('#finance').css('display','none');
$('#local').css('border','1px solid white');
The second way of achieving this is by chaining all of the elements and methods into one statement by utilizing the end() method. Th e end() method puts a stop on the current methods and allows you to start chaining new methods again after it, without any overlap of the methods before the end() method.
$('#news').find('#politics').css('border','1px solid blue').end().find('#finance').hide().end().find('#local').css('border','1px solid white');
0 comments:
Post a Comment