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.

Let's get straight to it.
 

<ul>
  <li><a href="#">Navi1</a></li>
  <li><a href="#">Navi2</a></li>
  <li><a href="#">Navi3</a></li>
  <li><a href="#">Navi4</a></li>
</ul>

Imagine, you want to listen to a user's clicks on all above links. So instead of binding four Event Listeners to each list-element, we only bind one listener to the root object called document.

The event target will get bubbled up in Internet Explorer and on other browsers the event and its target will be captured inside the nested html elements of the document object.

This is the JavaScript code to capture and filter the events and its targets:
 

document.onclick = function(event) {

   // IE8 bubbles instead of capture events
   event = event || window.event;
   var target = event.target || event.srcElement;

   for (i=1; i<8; i++) {
      if (target.innerHTML === "Navi" + i ) {
         return alert("You " + event.type + "ed on " + target.innerHTML);
      }
   }
}

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.

comments powered by Disqus