224

Can anyone please explain event delegation in JavaScript and how is it useful?

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Xenon
  • 2,257
  • 3
  • 14
  • 4
  • 2
    It's be nice if there was a link to smoe useful source of information about this. 6 hours in, this is the google top hit for "dom event delegation". Maybe this is a useful link? I'm not entirely sure: http://www.w3.org/TR/DOM-Level-2-Events/events.html – Sean McMillan Nov 06 '09 at 19:05
  • Or maybe this: http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/ – Sean McMillan Nov 06 '09 at 19:07
  • 7
    This is a popular one. Even fb guys link to this for their reactjs page https://davidwalsh.name/event-delegate – Sorter Nov 09 '15 at 10:24
  • See this https://javascript.info/event-delegation it will help you a lot – Suraj Jain Apr 09 '18 at 02:40

11 Answers11

351

DOM event delegation is a mechanism of responding to ui-events via a single common parent rather than each child, through the magic of event "bubbling" (aka event propagation).

When an event is triggered on an element, the following occurs:

The event is dispatched to its target EventTarget and any event listeners found there are triggered. Bubbling events will then trigger any additional event listeners found by following the EventTarget's parent chain upward, checking for any event listeners registered on each successive EventTarget. This upward propagation will continue up to and including the Document.

Event bubbling provides the foundation for event delegation in browsers. Now you can bind an event handler to a single parent element, and that handler will get executed whenever the event occurs on any of its child nodes (and any of their children in turn). This is event delegation. Here's an example of it in practice:

<ul onclick="alert(event.type + '!')">
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>

With that example if you were to click on any of the child <li> nodes, you would see an alert of "click!", even though there is no click handler bound to the <li> you clicked on. If we bound onclick="..." to each <li> you would get the same effect.

So what's the benefit?

Imagine you now have a need to dynamically add new <li> items to the above list via DOM manipulation:

var newLi = document.createElement('li');
newLi.innerHTML = 'Four';
myUL.appendChild(newLi);

Without using event delegation you would have to "rebind" the "onclick" event handler to the new <li> element, in order for it to act the same way as its siblings. With event delegation you don't need to do anything. Just add the new <li> to the list and you're done.

This is absolutely fantastic for web apps with event handlers bound to many elements, where new elements are dynamically created and/or removed in the DOM. With event delegation the number of event bindings can be drastically decreased by moving them to a common parent element, and code that dynamically creates new elements on the fly can be decoupled from the logic of binding their event handlers.

Another benefit to event delegation is that the total memory footprint used by event listeners goes down (since the number of event bindings go down). It may not make much of a difference to small pages that unload often (i.e. user's navigate to different pages often). But for long-lived applications it can be significant. There are some really difficult-to-track-down situations when elements removed from the DOM still claim memory (i.e. they leak), and often this leaked memory is tied to an event binding. With event delegation you're free to destroy child elements without risk of forgetting to "unbind" their event listeners (since the listener is on the ancestor). These types of memory leaks can then be contained (if not eliminated, which is freaking hard to do sometimes. IE I'm looking at you).

Here are some better concrete code examples of event delegation:

Crescent Fresh
  • 107,974
  • 25
  • 151
  • 138
  • I have got access forbidden on opening your third link Event delegation without a javascript library and +1 for your last link – bugwheels94 Jul 15 '13 at 12:46
  • Hello, thank you for a great explanation. I am still confused about a certain detail though: The way I understand the DOM tree event flow (As can be seen in [3.1. Event dispatch and DOM event flow](https://www.w3.org/TR/uievents/) ) the event object propagates until it reaches the target element then bubbles up. How come it can reach child elements of a node if the parent of this node is the event target in question? e.g. how can the event propagate to a `
  • ` when it should stop at `
      `? If my question is still unclear or needs a separate thread I'd be happy to oblige.
  • – Imad Apr 11 '17 at 09:14
  • @Aetos: *> How come it can reach child elements of a node if the parent of this node is the event target in question?* It cannot, as I understand it. The event finishes phase 1 (capturing) at the parent of the target, enters phase 2 (target) on the target itself, then enters phase 3 (bubbling) starting on the parent of the target. Nowhere does it reach a child of the target. – Crescent Fresh Apr 12 '17 at 15:01
  • @Crescent Fresh well then how does the event apply on the child node if it never reaches it? – Imad Apr 12 '17 at 15:19
  • @Aetos: I see where you're coming from. I think the confusion stems from thinking that it is the `onclick=...` that sets up event propagation. It's not. The spec is defining what a DOM/browser implementation *should do* when an event occurs. A "click" event (for example) is dispatched by the implementation as a result of a user action, irrespective of `onclick=...` being present in the code or not! It is only during the propagation of this event that the implementation should look for event listeners and invoke them. The `onclick=` simply registers a listener... – Crescent Fresh Apr 12 '17 at 17:41
  • ...So you see, the "child" node as you are calling it in this example is actually the event's target! – Crescent Fresh Apr 12 '17 at 17:41
  • @Roland: OP asked the question then left the site 33 mins later, hasn't been seen since :) – Crescent Fresh Jan 31 '18 at 17:43
  • Shouln't we use event capturing for event delegation, will save lot of time, as event won't have to bubble up? – Suraj Jain Apr 09 '18 at 03:02
  • Wow. Really nice explanation. Thank you! – Samuel Jan 19 '19 at 14:44
  • 1
    Really Great answer. Thanks for explaining event delegation with relevant facts. Thanks! – Kshitij Oct 01 '19 at 12:44