What is Event Delegation in 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>
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.
Resources:
π More Webtips
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: