Advertisement
  1. Code
  2. JavaScript

Quick Tip: JavaScript Event Delegation in 4 Minutes

Scroll to top
Read Time: 3 min

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.

1
$('ul').click(function(e) {
2
	
3
	if ( $(e.target).is('a') ) {
4
		alert('clicked');
5
	}
6
});

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.

1
<ul>
2
   <li><a href="#">Anchor</a></li>
3
</ul>

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:

1
// Get some unordered list, which contains anchor tags
2
var ul = document.getElementById('items');
3
4
// Quick and simple cross-browser event handler - to compensate for IE's attachEvent handler
5
function addEvent(obj, evt, fn, capture) {
6
	if ( window.attachEvent ) {
7
		obj.attachEvent("on" + evt, fn);
8
	}
9
	else {
10
		if ( !capture ) capture = false; // capture
11
		obj.addEventListener(evt, fn, capture)
12
	}
13
}
14
15
// Check to see if the node that was clicked is an anchor tag. If so, proceed per usual. 
16
addEvent(ul, "click", function(e) {
17
  // Firefox and IE access the target element different. e.target, and event.srcElement, respectively.
18
  var target = e ? e.target : window.event.srcElement;
19
  if ( target.nodeName.toLowerCase() === 'a' ) {
20
     alert("clicked");
21
     return false;
22
  }
23
});
Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.