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>
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
Tired of looking for tutorials?
You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.
📚 Get access to exclusive content
Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. ☕Get access