Hidden advantage of event delegation


Nowadays, everybody has (or should) heard of event delegation, the new gray in javascript. It has many advantages, such as cutting down on the event handlers javascript needs to set on a page. But there is one advantage, that not many people talk about. So I will.

First we will start with the most talked about stuff, to refresh your memory, or to give you a short introduction in the matter. In short there are two kinds of calling your events from your html, inline scripting and unobtrusive javascript. The latter has a variation called Event Delegation.

Inline scripting is the one we all know and the one that is not considered Best practice anymore. What you do is call the event from inside your html, like this:

<li onclick= "alert('foo');">inline script</li>

The disadvantages of this are multiple, one is maintenance, file size is another.

The correct way to do this, as all the cool kids know, is with unobtrusive javascript. That way you have smaller file size, easier maintenance and so on. So what you do in html is:


And you set your events with the javascript on load, page ready or what not:

// go through the dom and attach a click on every li
	// do something when clicked.

This is a step up, but it has a couple of disadvantages. As the number of event handlers grow, the time needed to add them increases. Not that this is a problem on any real browsers, but as long as IE6 continues to be used, you have to work with slow browsers. Enter Event Delegation.

With event delegation the amount of events you have to attach shrinks by a lot, as you can put them fairly high up, like on the body. So with identical html, in your javascript you do something like this:

// attach a click handler on the body (one)
	// when a li is the event target do stuff
	'li': function() { alert('foo'); }

This generates only one event handler, making it way faster another advantage of event delegation comes into play when you add elements to the dom, you don't need to attach the events again, as the handler is attached to a higher level.

So here is the deal, not only you get less code, you get even lesser code. Everybody wins!

Here are some links about event delegation should you be wanting to know more... (you can always ask me on twitter).

Here are the files I used for testing, first the inline scripting example, than the unobtrusive javascript one and last but not least the one with event delegation, have fun researching...

← Home