Advertisement
JavaScript & AJAX

Quick Tip: JavaScript Event Delegation in 4 Minutes

by

Event delegation can be a confusing topic for those who are unfamiliar with the concept. But, luckily, it's really simple. In this quick tip video tutorial, I'll demonstrate the concept in just under four minutes.

Imagine that you have five hundred anchor tags on your page. As you might imagine, adding a click event to every one of those would be time consuming, and unnecessary. On top of that, what happens if, once you click on those anchor tags, we add additional anchor elements to the page? Would those new anchors be bound to the click event as well? The answer is no. You would then have to reattach a listener to those newly created elements.

Enter Event Delegation

Instead, with event delegation, we simply add a single event listener to an ancestor element, maybe something like a "ul." Then, when the user clicks on one of its child elements, like an anchor tag, we only check to see if the target of the click was, in fact, an anchor tag. If it was, we proceed per usual.

$('ul').click(function(e) {
	
	if ( $(e.target).is('a') ) {
		alert('clicked');
	}
});

Advantages

  • Only attach one event listener to the page, rather than five hundred (in our example)
  • Dynamically created elements will still be bound to the event handler.

Why Does this Work?

It works because of the way elements are captured (not IE) and bubble up. For instance, consider the following simple structure.

When you click on the anchor tag, you're also clicking on the 'li' and the 'ul' and even the 'body' element. This is referred to as bubbling up.

Notes About this Screencast

Please keep in mind that this is just a simple example to explain the functionality. We used jQuery, only because I had four minutes to record! In that particular example (watch the screencast first), we could have used two alternative options:

  1. Pass true as a parameter of the clone() method. This would then clone the element, as well as any event handlers.
  2. Use the live() method instead. However, be careful when using this method: it reattaches the event handler X times. This may not necessarily be needed.

Mostly, this was meant to demonstrate the idea. With regular JavaScript, you could do something like:

// Get some unordered list, which contains anchor tags
var ul = document.getElementById('items');

// Quick and simple cross-browser event handler - to compensate for IE's attachEvent handler
function addEvent(obj, evt, fn, capture) {
	if ( window.attachEvent ) {
		obj.attachEvent("on" + evt, fn);
	}
	else {
		if ( !capture ) capture = false; // capture
		obj.addEventListener(evt, fn, capture)
	}
}

// Check to see if the node that was clicked is an anchor tag. If so, proceed per usual. 
addEvent(ul, "click", function(e) {
  // Firefox and IE access the target element different. e.target, and event.srcElement, respectively.
  var target = e ? e.target : window.event.srcElement;
  if ( target.nodeName.toLowerCase() === 'a' ) {
     alert("clicked");
     return false;
  }
});
Related Posts
  • Web Design
    Complete Websites
    Finishing the Responsive Timeline Portfolio PagePortfolio2 thumb
    It's time to finish off our responsive timeline portfolio layout. In this tutorial we'll add some flair with CSS3 animations and jQuery.Read More…
  • Code
    JavaScript & AJAX
    Connect 4 With Socket.ioSocket io wide retina preview
    Today we'll see how we can use Node.js and Socket.io to create a multiplayer Connect 4 style game.Read More…
  • Code
    JavaScript & AJAX
    Working With IndexedDB - Part 3Indexeddb retina preview
    Welcome to the final part of my IndexedDB series. When I began this series my intent was to explain a technology that is not always the most... friendly one to work with. In fact, when I first tried working with IndexedDB, last year, my initial reaction was somewhat negative ("Somewhat negative" much like the Universe is "somewhat old."). It's been a long journey, but I finally feel somewhat comfortable working with IndexedDB and I respect what it allows. It is still a technology that can't be used everywhere (it sadly missed being added to iOS7), but I truly believe it is a technology folks can learn and make use of today. In this final article, we're going to demonstrate some additional concepts that build upon the "full" demo we built in the last article. To be clear, you must be caught up on the series or this entry will be difficult to follow, so you may also want to check out part one.Read More…
  • Code
    Mobile Web Apps
    Create a Location-Aware Site with Sencha Touch - Displaying LocationsLogo
    This tutorial will guide you through the development of a Location-based mobile website using the Google Place search engine and Sencha Touch 2.1 . This is the second in a two-part series, and today we'll learn how to display map markers and location details.Read More…
  • Code
    JavaScript & AJAX
    jQuery Succinctly: Events & jQueryJquery cover
    Not Limited To a Single ready() Event It is important to keep in mind that you can declare as many custom ready() events as you would like. You are not limited to attaching a single .ready() event to the document. The ready() events are executed in the order that they are included.Read More…
  • Code
    JavaScript & AJAX
    From jQuery to JavaScript: A ReferenceJquerytojavascript
    Whether we like it or not, more and more developers are being introduced to the world of JavaScript through jQuery first. In many ways, these newcomers are the lucky ones. They have access to a plethora of new JavaScript APIs, which make the process of DOM traversal (something that many folks depend on jQuery for) considerably easier. Unfortunately, they don't know about these APIs! In this article, we'll take a variety of common jQuery tasks, and convert them to both modern and legacy JavaScript.Read More…