Event delegation in JavaScript

Saurabh Mhatre
2 min readJul 20, 2023

--

Event delegation in JavaScript

Event delegation is a technique in JavaScript where you handle events on a parent element rather than attaching individual event handlers to its child elements. By doing this, you can take advantage of event bubbling, where events triggered on a child element will "bubble up" through its ancestors until it reaches the specified parent element.

This approach is particularly useful when dealing with dynamically added or large numbers of child elements because it helps reduce the number of event handlers and improves performance.

Let's take an example to illustrate event delegation:

HTML:

```html
<div id="parent">
<button class="child-button">Button 1</button>
<button class="child-button">Button 2</button>
<button class="child-button">Button 3</button>
</div>
```

JavaScript:


// Get the parent element
const parentElement = document.getElementById('parent');
// Add a single event listener to the parent element
parentElement.addEventListener('click', function(event) {
// Check if the target element (where the event originated) is a button
if (event.target && event.target.matches('.child-button')) {
// Handle the button click event
const buttonText = event.target.textContent;
console.log(`Button "${buttonText}" was clicked.`);
}
});

In this example, we have a parent `<div>` element with three child `<button>` elements. Instead of adding individual event listeners to each button, we add a single event listener to the parent element. When a button is clicked, the click event will bubble up from the clicked button to the parent element. The event listener then checks if the target element (the element where the event originated) matches the selector `.child-button`. If it does, it means that a button was clicked, and the desired action (in this case, logging the button text) is performed.

By using event delegation, we achieve a more efficient event handling mechanism, especially if we have a large number of buttons or if buttons are dynamically added or removed from the parent container. It reduces memory usage and minimizes the potential for memory leaks caused by attaching and detaching event handlers on child elements.

--

--

Saurabh Mhatre
Saurabh Mhatre

Written by Saurabh Mhatre

Senior Frontend Developer with 9+ years industry experience. Content creator on Youtube and Medium. LinkedIn/Twitter/Instagram: @SaurabhNative

No responses yet