Event Delegation
What is Event Delegation?
Event delegation is a technique in JavaScript where an event handler is attached to a parent element, rather than to each child element separately.
This technique works thanks to the event bubbling mechanism — an event first occurs on the target element, then bubbles up through the DOM tree.
Simple Example
Suppose you have a list:
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
Instead of attaching a click handler to each <li>, you can attach one handler to <ul>:
const menu = document.getElementById("menu");
menu.addEventListener("click", (event) => {
const target = event.target;
if (target.tagName === "LI") {
console.log("You clicked on:", target.textContent);
}
});
How Does it Work?
- User clicks on
<li>. - Event bubbles from
<li>to<ul>. - Handler on
<ul>catches this event. - We check
event.targetto understand which exact element was clicked.
Advantages of Event Delegation
- Fewer handlers → less memory consumption.
- Works with dynamic elements that weren't initially in DOM.
- Simplifies event management when DOM changes.
Disadvantages and Cautions
- Always need to check
event.targetto ensure event occurred on the right element. - May have unwanted behavior if DOM structure changes dynamically.
- Doesn't work if event doesn't bubble (e.g.,
blur,focus,scroll— for them you need to usecapture).
Tip:
Delegation is especially useful when you have many similar elements and want to attach a handler once — efficient and clean.