MediumConcept

What is event delegation in JavaScript?

Technology:
JavaScript
Experience:
Junior,
Mid-level

Quick answer

Event delegation means attaching one listener to a parent element and using event bubbling to handle events from its children, instead of adding a listener to each child.

Detailed explanation

When you click a child element, the event bubbles up through its ancestors. A single listener on the parent can inspect event.target (or use event.target.closest(selector)) to find which child was clicked and react accordingly.

This uses less memory for long lists and also works for elements added later, because the listener lives on the parent. It does not work for events that do not bubble, such as focus and blur (use focusin and focusout instead).

Example

javascript
document.querySelector("#todo-list").addEventListener("click", (event) => {
  const item = event.target.closest("li[data-id]");
  if (!item) return;
  removeTodo(item.dataset.id);
});
  • JavaScriptMedium

    What is the event loop in JavaScript and how does it work?

    The event loop is the mechanism that lets single-threaded JavaScript handle asynchronous work: it runs the call stack to empty, then runs all queued microtasks (promises), then takes the next task (timers, events) from the queue.

    Mid-level · Senior · Asynchronous Programming
  • HTMLMedium

    What is the difference between async and defer on script tags?

    Both download the script without blocking HTML parsing. defer waits until parsing finishes and runs scripts in document order; async runs a script as soon as it is downloaded, which can be before or after parsing and in any order.

    Mid-level · Senior · Browser & DOM
  • HTMLMedium

    How does the browser render a web page?

    The browser parses HTML into a DOM and CSS into a CSSOM, combines them into a render tree, computes layout (reflow), paints pixels and composites layers onto the screen.

    Mid-level · Senior · Browser & DOM
  • JavaScriptHard

    How do you find and fix memory leaks in JavaScript?

    Take heap snapshots in Chrome DevTools before and after the suspect action, compare what grew, and fix the retaining reference, which is usually a forgotten listener, timer, global variable or unbounded cache.

    Senior · Memory Management