The New Way to do Event Bubbling

All Javascript developers should be familiar with event bubbling. For those of you who don’t know, event bubbling is when DOM events move up the chain from bottom to top. In other words, if you click on a <li>, the <body> will get clicked first, then the <ul>, then the <li>. In IE, of course, it does the exact opposite (“event capturing”), but with the advent of jQuery, this is pretty much a moot point.

So why is it important to know? Well, imagine you’ve attached a click event to an <li>. It may not be a problem now, but if your <ul> ends up with thousands of <li>s, you’ve got thousands of bindings in the DOM, which is going to be a performance killer among other things. Instead, simply attach the click event to the <ul>, then inside the event, figure out what <li> got clicked on and react accordingly.

By the way, this is an interview question for every Javascript-related job ever. Know what it is and why it’s important.

I was going to post a simple example on how to do this, but apparently this is entirely the point of jQuery’s new “on” method. I use “on” all the time, and you should too, and if you are still using “delegate” or the dreaded “live” to bind events dynamically, you should start using “on” instead. So anyway, here is how to use “on” to efficiently bubble events:

$('ul').on('click','li', function(evt){
alert("cream cheese");

What this code is doing is binding to the <ul>, but only firing the callback if a child <li> node was targeted. I’ve always used $(document).on as a force of habit, but really you should be using the parent of the object you want to bind to. Folks, it doesn’t get any simpler than this. Sure wish I understood this months ago….

Leave a Reply

Your email address will not be published. Required fields are marked *