Learn JQuery Step By Step Part 6: Chaining

One of the coolest things about JQuery is the ability to chain functions. Chaining refers to “the art” of executing several functions on an object in one line.

The following example uses the functions hide() and show() to hide and then show a red div tag. Please pardon the inline CSS ;)

<div id="square" style="background-color:red;">
	<h1>Look, I can contract and expand!</h1>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
	$("#square").hide(5000).show(5000);
});
</script>

The same effect could be accomplished by chaining two toggle()s, like this.

<script type="text/javascript">
$(document).ready(function(){
	$("#square").toggle(5000).toggle(5000);
});
</script>

Can you see how chaining saves you from typing the following?

	$("#square").hide(5000);
	$("#square").show(5000);
        // or
       $("#square").toggle(5000);
       $("#square").toggle(5000);

Pretty cool right?!

blog comments powered by Disqus