Loading...
Loading...
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.
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);
}
});
<li>.<li> to <ul>.<ul> catches this event.event.target to understand which exact element was clicked.event.target to ensure event occurred on the right element.blur, focus, scroll — for them you need to use capture).Tip:
Delegation is especially useful when you have many similar elements and want to attach a handler once — efficient and clean.