Event Delegation

In the early days of JavaScript the only option available for event processing was to attach event handlers directly inside the HTML itself. This meant that if you had lots of elements in the page that you wanted to apply JavaScript interaction to that you ended up with some huge HTML due to all of the event handlers that the code needed to attach the JavaScript.

The introduction of the DOM and event listeners means that the situation is completely different today. Gone is the need to attach event handlers inside the HTML itself. Gone to is the need to use event handlers as event listeners are far more flexible.

With event listeners you don't even need to attach a listener to every element that you want to use it. Instead you can use event delegation. With delegation you attach the listener to a higher level element within the page. That listener can then provide the required processing for any element it is wrapped around that you want to react to that event. Listeners can tell which element it was that actually triggered the listener even when the triggering element is nested several layers deep inside the element that the listener is attached to.

The following shows all of the code we meed to implement event delegation for any event processing that we want to attach to our page. The addEvent function is a wrapper around addEventListener to save us the trouble of having getElementById in all of the calls where we want to attach the listener to an element identified by an id (not that we will need as many listeners when we use delegation). The whichElement function is the one that figures out which element our visitor was trying to interact with when they triggered the event. The myfunc function simply shows how we use whichElement in our event processing. In the code that we use in place of the comment in that function the x variable is a reference to the element they interacted with allowing us to have the code interact with that specific element rather than the one the event listener is attached to.

(function() {
"use strict";
var addEvent, whichElement, myfunc;
addEvent = function(ob, type, fn ) {
if ('string' === typeof ob) ob = document.getElementById(ob);
ob.addEventListener(type, fn, false );
whichElement = function(e) {
var targ = e.target;
if (3===targ.nodeType) {
targ = targ.parentNode;
return targ;
myfunc = function(e) {
var x = whichElement(e);
// processing goes here
addEvent('elem', 'click', myfunc);


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow