JavaScript - Event Delegation in JavaScript
Event delegation is a technique in JavaScript where a single event listener is attached to a parent element instead of attaching event listeners to multiple child elements. When an event occurs on a child element, the event bubbles up through the DOM hierarchy and is captured by the parent element’s event listener.
This technique works because of the event bubbling mechanism in the Document Object Model. When an event such as a click occurs on an element, it first runs on the target element and then propagates upward to its parent elements.
Using event delegation improves performance and simplifies code when working with many elements.
Example without event delegation:
If a page contains many buttons, each button might have its own event listener.
const buttons = document.querySelectorAll("button");
buttons.forEach(function(button) {
button.addEventListener("click", function() {
console.log("Button clicked");
});
});
In this case, every button has its own event listener. If there are hundreds of buttons, it increases memory usage and makes code harder to maintain.
Example using event delegation:
Instead of attaching an event listener to each button, a single event listener is attached to their parent element.
document.getElementById("container").addEventListener("click", function(event) {
if (event.target.tagName === "BUTTON") {
console.log("Button clicked");
}
});
Here, the event listener is attached to the container element. When a button inside the container is clicked, the event bubbles up to the container. The code checks whether the clicked element is a button and then performs the required action.
Advantages of event delegation:
It improves performance because fewer event listeners are used.
It makes code easier to manage when many elements exist.
It works well with dynamically added elements because new elements automatically inherit the event behavior.
Event delegation is widely used in modern JavaScript applications, especially when dealing with lists, tables, menus, and dynamically generated content.