What is Event Delegation in JavaScript?

What is Event Delegation in JavaScript?

Ferenc Almasi β€’ 2020 October 19 β€’ πŸ“– 1 min read

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:

<!-- 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
Copied to clipboard!

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
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Resources:

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended