Event Delegation Example

Date: October 22, 2006

Component: Event, Dom

Version: v0.11.4

  • List Item 1
  • List Item 2
  • List Item 3
  • List Item 4
  • List Item 5
  • List Item 6

In this YDN-JavaScript post, prizeloop asks whether "event delegation" — the use of a single event listener on a parent object to listen for events happening on its children (or deeper descendants) — works for mousemove events as well as, say, click events. This example illustrates the use of event delegation on both click and mouseover events.

We'll start with some structural markup — a div containing a ul with n li children.

We'll use the YUI Logger Control as the reporting mechanism for our event handlers, so this example begins its script by creating a LogReader instance and rendering it into the document body on pageload:

Now we'll add an event handler to the container div, listening for any clicks in that div's bounds. We're only really interested in clicks on li's, though; when we get one of those, we'll write out a message to the Logger.

The same technique works for the mousemove event as well. We'll substitute mousemove for click, but make no other substantive changes:

In this example, we've used two event listeners with their associated memory and performance load to serve as delegates for the same two events on six list items. Instead of 12 event listeners, we now have two. And the code works regardless of the number of li's used. In a more complicated page context, it's easy to see how this technique can dramatically reduce the number of event listeners required and thereby improve the performance of your application.

Eric Miraglia, Yahoo Presentation Platform Engineering

(c)2010 Yahoo Inc.