A list with 1,000 rows does not need 1,000 click listeners. Events bubble up from the element that was clicked through all of its ancestors, so a single listener on a shared parent can see every click and work out which row it came from. This pattern is called event delegation, and it also works for rows that are added after the listener was set up.
Write a delegate function that sets up one listener on root and calls handler whenever the event came from an element inside root that matches selector.
const list = document.querySelector("#todo-list")!;
const off = delegate(list, "click", "li.todo", function (event, item) {
// `item` (and `this`) is the <li class="todo"> that was clicked,
// even when the click landed on a <span> or <b> inside it.
item.classList.toggle("done");
});
// Rows added later are handled too, without adding listeners.
list.insertAdjacentHTML("beforeend", `<li class="todo"><span>Buy milk</span></li>`);
off(); // stop listening
Requirements
- Add exactly one listener to
root for eventType, whatever the number of matching elements.
- Start at
event.target and walk up through its ancestors until you reach root. Call handler once for every element on that path that matches selector, innermost first.
- Call the handler with
this set to the matched element, and the arguments (event, matchedElement).
root itself and elements above it never count as a match, even if they match selector. Events from outside root are ignored.
- If the event target is a text node, start from its parent element.
- If a handler calls
event.stopPropagation(), do not call the handler for the outer matches.
options.capture (default false) is passed on to addEventListener. This lets you delegate events that do not bubble, such as focus and blur.
root can be an element or the document.
- Return a function that removes the listener. Calling it more than once is safe.
Follow-up: which common events do not bubble, and what are their bubbling alternatives? Why is capture enough to delegate them anyway?