Menu

Event Delegation in JavaScript

The next logical step up, respectively down-level from using CSS3 Selectors together with JavaScript libraries to select specific DOM elements, is to write your own JavaScript to control your markup.

So in order to completely seperate behaviour (JavaScript) from presenation (HTML) and content (REST, JSon, XML, etc..) you might want use Events and Event-Handling in JavaScript. Now, the downside in applying many Event Listeners to many DOM elements bears the risk of memory leakage, CPU overhead and therefore overall loss of performance; especially on mobile devices.

A solution to minimize these shortcomings of Event Listener usage comes from Yahoo!. They implemented a technique called Event Delegation in their User Interface Library YUI. They showed the Developer Community how to use a year old browser behaviour, that is even officially specified in the W3C DOM Specification.

First we bind the onclick Event Listener to the document object. Then we pass down the event so that we can access its target or source (IE). Then we filter the target with a for-loop for its containing text and simply alert the results. Please spare me details on how proprietary innerHTML is, which was invented by Microsoft. You may test this example here: Delegation Example.