Event delegation is a pattern in which a single event listener is attached to a common ancestor of multiple elements. Instead of attaching an event handler to each individual element, you delegate the responsibility to a parent element.
This is particularly useful for handling events on dynamically added elements, as well as improving performance by minimizing the number of event handlers.
Let’s understand it with a real-world example.
Let’s imagine you’re hosting a big party with lots of guests. Now, think of each guest as an element on a webpage, like a button or a link. Instead of individually checking and handling every guest’s actions, you decide to let the party venue staff take care of it.
In JavaScript, we call this type of concept “Event Delegation.” It’s like appointing someone to handle actions on behalf of many elements. Instead of attaching an event listener to each button, you attach one to a common parent element (like the entire party venue).
So, when a guest (button or link) does something, like clicking, the event bubbles up to the parent (the party venue). The appointed staff (event listener) at the venue checks who did the action and takes the appropriate action for that specific guest.
This way, you save time and resources, just like how in event delegation, you handle events for multiple elements efficiently by relying on a common parent instead of attaching listeners to each individual element. It’s like having a party planner who manages everything for you, making the event more organized and less overwhelming.
Event Delegation Example
Consider a scenario where you have a list of items, and you want to log a message when any item is clicked. Instead of attaching an event listener to each item, you can delegate the event handling to the parent container.
<ul id="itemList"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <!-- More dynamically added items can be added here --> </ul>
<script> // Event delegation for the entire list document.getElementById("itemList").addEventListener("click", function(event) { // Check if the clicked element is an 'li' element if (event.target.tagName === 'LI') { var clickedItem = event.target.textContent; console.log("Clicked on:", clickedItem); } }); // Simulating the addition of a new item dynamically setTimeout(function() { var newItem = document.createElement("li"); newItem.textContent = "Item 4 (Dynamically Added)"; document.getElementById("itemList").appendChild(newItem); }, 3000); </script>
In this JavaScript example, the event listener is attached to the #itemList
element using addEventListener
.
The event object is then checked to see if the target element (the element that triggered the event) is an li
element. If it is, the click event is handled.
The dynamically added item will also trigger the same event handler, demonstrating the concept of event delegation in pure JavaScript.
More Tricks
Being tricky 😉