If there is one thing jQuery puts forward, it’s chaining. It’s one of the core reasons of it’s motto “jQuery is designed to change the way that you write JavaScript”. While chaining can be quite useful it is not that obvious what happens behind the scene to get this magic at work.

Chaining in jQuery

In fact chaining is more easy than you would think, the key is to define methods inside an object. Let’s have a look at a typical jQuery example, $(“.blabla”).addClass(“test”). $(“.blabla”) is in fact a call to the function jQuery(). The key to get your chaining going is to understand that jQuery() is an object with methods that you can call directly using the dot notation.

A very simple example of how you could do chaining

 
 <div id="myid"></div>
<script type="text/javascript">
		posAbsolute("myid").html("you made my day");  
 
		function posAbsolute(elementId){
			var node = document.getElementById(elementId)
 
			return{
     // I return the method html that can now be used in my chaining
				html : function(content){
					node.innerHTML = content;
				}	
			};
		}
</script>

View demo

Not that hard after all

Personally I am really not fan of long chaining, but if your starting to do javascript api’s, that can be a nice trick to use to put a more user friendly face on top of it. Especially if it is intended to beginner javascript developers. It is just one example that shows how javascript really has a big expressive power.

2 thoughts on “Understanding chaining in javascript and jQuery

  1. Good Post. This can be very helpful when working with node.js. You can easily end up with messy spaghetti code using a lot of call backs but if you architect your project with chaining in mind it will be easier to work with.

Comments are closed.