Imagine you’re the principal of a large school. Every day, students (like buttons, links, or images on a webpage) send you notes (like “clicks” or “taps”). If you tried to handle every student’s note personally, you’d be overwhelmed. Instead, you assign one teacher per class (more like a parent container) to collect notes from their students. When a note arrives, the teacher tells you, “Someone in Class 3B sent this.” You then check who it’s from and act accordingly.
This is event delegation in JavaScript!
Event delegation is a technique in JavaScript where you assign a single event listener to a parent element (like a container, list, or table) to manage interactions with multiple child elements inside it, instead of attaching listeners to each child individually.
<div> wrapping all buttons) handles everything. Fewer listeners = better performance.2. Flexibility:
3. Simplicity:
When you click a button:
targetproperty.Imagine we want to have a to-do list where clicking on any task marks it as complete. We can do it without delegation or we can do it with delegation.
//Without Delegation (Messy)
// Add a listener to EVERY task (inefficient!)
document.querySelector("#task-1").addEventListener("click", markComplete);
document.querySelector("#task-2").addEventListener("click", markComplete);
// ...and so on for 100 tasks 😅
//With Delegation// ONE listener on the parent <ul>:
document.querySelector("#todo-list").addEventListener("click", function(event) {
// Check if a task (<li>) was clicked:
if (event.target.tagName === "LI") {
event.target.classList.add("complete"); // Mark it done!
}
}); event.target to identify the clicked element.Latest tech news and coding tips.
1. What Is the Golden Ratio? The Golden Ratio, represented by the Greek letter φ (phi), is…
In CSS, combinators define relationships between selectors. Instead of selecting elements individually, combinators allow you to target elements based…
Below is a comprehensive, beginner-friendly, yet deeply detailed guide to Boolean Algebra, complete with definitions, laws,…
Debugging your own code is hard enough — debugging someone else’s code is a whole…
Git is a free, open-source distributed version control system created by Linus Torvalds.It helps developers: Learn how to…
Bubble Sort is one of the simplest sorting algorithms in computer science. Although it’s not…