What is Event Delegation in JavaScript?

What is Event Delegation in JavaScript?

Ferenc Almasi β€’ 2020 October 19 β€’ Read time 1 min read
  • twitter
  • facebook
JavaScript

DOM event delegation is used for responding to user events via a single parent rather than each child node. With it, you can bind an event handler to a common parent element that will handle any event happening on one of its children:

Copied to clipboard! Playground
<!-- Instead of doing: -->
<ul>
    <li onclick="console.log(event.type);">πŸ“•</li>
    <li onclick="console.log(event.type);">πŸ“™</li>
    <li onclick="console.log(event.type);">πŸ“—</li>
</ul>

<!-- We can do: -->
<ul onclick="console.log(event.type);">
    <li>πŸ“•</li>
    <li>πŸ“™</li>
    <li>πŸ“—</li>
</ul>
event-delegation.html

This has a couple of advantage over of using event listeners on individual elements:

  • You can respond to user events with one listener, which creates a leaner and more readable code.
  • You don’t need to rebind events if nodes are added
    through JavaScript.
What is Event Delegation in JavaScript?
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.