One listener for a whole row of buttons: event delegation, explained plainly
The order page lists 24 dishes, and clicking one adds it to the order — all through event bubbling. This guide follows MDN's addEventListener, event bubbling, target, closest, matches, and stopPropagation references: bubbling vs capturing, target vs currentTarget, delegation itself, the closest() safety net, new nodes, stopping propagation, once, passive, signal, anonymous functions, this, and passing parameters with closures.

First, the boundaries. The site already has “The page is a tree: DOM querying and traversal”, about finding nodes in the page tree; “When exactly does your code run? The JavaScript event loop”, about when code executes; and the search-box debounce guide, about input interaction. This guide covers none of those. It covers one thing: how events such as clicks and key presses travel from one element to another, and how one listener can take care of a whole row of buttons. The “Greenstone Cafe” below is the same fictional practice project as before: a small web tool that takes orders for a street-corner cafe. This time it is the order page: the menu list has 24 dishes, one button per dish, and clicking one adds it to the order. Every operation, code sample, and number built around it is invented to explain the technique, not a real record. Everything about event syntax and behavior comes from six MDN reference pages — “EventTarget: addEventListener() method”, “Event bubbling”, “Event: target property”, “Element: closest() method”, “Element: matches() method”, and “Event: stopPropagation() method”. The sources are listed in this article's meta information and evidence record. The examples in the docs — the table with id “outside”, the 16 colored tiles, the list of three birds, the video box — are the docs' own examples, not real services.
Step 1: Click one button and the whole ancestor chain hears it — bubbling
Start with the simplest case. A button sits inside a div, and the div sits inside the body. Attach a click handler to the button, the div, and the body, then click the button: all three handlers run, in the order button, then div, then body. MDN puts it plainly: the event bubbles up from the innermost element that was clicked. Clicking the button is also implicitly clicking the div that holds it, and the body that holds the div. That is called bubbling. The Greenstone Cafe order page tripped over this: a click handler on the menu list container was meant to close the menu when the blank area was clicked, but clicking a dish button to order also ran the container's handler, so the menu closed the moment an order was placed. Remember the first sentence: you click the innermost element, and the whole ancestor chain hears it.
Bubbling is sometimes a nuisance and sometimes exactly what you want. All of delegation depends on it. First, the other side of propagation, then back to how to use it.
Step 2: It works the other way too — capturing, off by default
Bubbling runs from the inside out. The opposite direction is called capturing: the least nested element fires first, then successively more nested elements, until the target is reached. MDN says capturing is disabled by default, and to enable it you pass the capture option to addEventListener(). Take the same button, div, and body: attach all three handlers with { capture: true }, click the button, and the order reverses — body first, then div, then button. MDN adds that by default almost all event handlers are registered in the bubbling phase, and that makes more sense most of the time. So the listeners you normally write all run in the bubbling phase; capturing is the other road, opened only when you ask for it. The cafe order page uses capturing in one place: a global notice bar at the top of the page logs every click first, using a listener in the capture phase, then lets the event travel on down. Remember the rule: without capture, it is bubbling; with capture: true, it is capturing.
Step 3: target is what was clicked, currentTarget is who is handling it
Two properties on the event object are easy to mix up: target and currentTarget. target is the element the event was initially fired on — the innermost element that was clicked. currentTarget is the element the handler that is currently running is attached to. As the event bubbles up, target stays the same the whole way — always that button. currentTarget changes: when the div's handler runs it is the div, when the body's handler runs it is the body. MDN states it plainly in the delegation example: use event.target to get the element that was the target of the event, and event.currentTarget to get the element that handled the event. The cafe order page tripped here: the container's handler read event.currentTarget, expecting the dish button that was clicked, and kept getting the container itself, so the same dish was added to the order every time. Switching to event.target got the button that was actually clicked. Remember the rule: to ask “what was clicked”, look at target; to ask “who is handling it now”, look at currentTarget.
Step 4: Delegation itself — one listener for a whole row
Now the core idea. MDN's definition: when you want some code to run when the user interacts with any one of a large number of child elements, set the event listener on their parent and have events that happen on them bubble up to their parent, rather than setting the event listener on every child individually. The docs' example is a wall of 16 tiles: a container holding 16 divs, and clicking a tile sets it to a random color. The clumsy way is one handler per tile. The delegated way is a single handler on the container, writing event.target.style.backgroundColor = bgChange() inside it, so whichever tile is clicked changes color. The cafe order page is written the same way: a single click listener on the menu list container (a ul), and whichever dish button is clicked, event.target is that button, and its data-id is read to add the dish to the order. Twenty-four dishes, one listener. Remember the rule: many children, same behavior — move the listener one level up and let the parent handle it.
Step 5: What if the click lands on the icon inside the button — closest() as a safety net
Delegation has a common weak spot: the button contains other things. A dish button holds a small icon, and clicking it hits the icon, not the button, so event.target is the icon and the dish id on the button cannot be read. MDN offers two tools for this. The first is closest(): it traverses the element and its parents, heading toward the document root, until it finds a node that matches the specified CSS selector. It returns the closest ancestor element or the element itself; if there is no such element, null is returned, and an invalid selector throws a SyntaxError. In delegation you write const button = event.target.closest("button"), and whether the click landed on the button itself or on the icon inside it, the button is found; if the click was nowhere near a button, closest() returns null, so check for null before going on. The second is matches(): it only answers one question — would this element be selected by the given CSS selector — returning true or false, and throwing a SyntaxError if the selector cannot be parsed. In delegation you can first check event.target.matches("button") to verify the identity, and return early if it does not match. The cafe order page uses both: matches() checks the identity, closest() finds the button, and clicks on the icon, the text, or the button edge all land correctly. Remember the rule: target is not always the element you want, so check its identity first, then walk up.
Step 6: Dishes added later need no new listener — delegation covers newcomers by nature
Delegation has a bonus: child elements added later need no listener of their own. The listener sits on the parent, so a click on a new node bubbles up to the parent all the same, and the same handler takes care of it. The other way around — one listener per button — means every new dish has to be wired up again, and a forgotten one simply does nothing when clicked. The cafe order page learned this the hard way: the menu switches by category, regenerating a batch of buttons each time, and the old code attached a listener to every dish, so after switching to the “new dishes” category the new buttons had nothing attached and clicking them did nothing. After switching to delegation, no matter how the categories change or the buttons are replaced, the one listener on the container is always there waiting. Remember the rule: if the list changes and nodes are added, do not wire them one by one — let the parent handle them all at once.
Step 7: When you do not want it to bubble up — stopPropagation()
Sometimes bubbling has to be stopped. MDN's video-box example is about exactly this: a page with a “Display video” button, a box holding a video, and the video inside the box. Click the button and the box appears; click the video and it starts playing; click the blank area inside the box and the box hides. The problem is that the video is inside the box, so clicking the video runs the video's handler, and then the event keeps bubbling to the box, whose handler runs too — the video starts playing and the box hides at the same moment. The fix is to call event.stopPropagation() inside the video's handler, then call video.play(), so the event stops at the video and never reaches the box. MDN defines stopPropagation() as preventing further propagation of the current event in the capturing and bubbling phases. The cafe order page has the same shape: an order card with a small “delete” button inside it, where clicking delete should remove just that order, not trigger the card's own “open to see details”. Calling stopPropagation() first in the delete handler, then deleting the order, keeps the card from being opened by mistake. Remember the rule: if only this level should act and the ancestors should not, call stopPropagation() at this level.
Step 8: Stopping bubbling is not stopping the default action
There are two things stopPropagation() does not do, and MDN says so on the same page. First, it does not prevent any default behaviors: click a link, stop the event from bubbling, and the link is still followed. To stop that behavior, use preventDefault(). Second, it does not prevent propagation to other event handlers of the current element: if two click handlers are attached to the same button and one calls stopPropagation(), the other still runs. To stop those as well, use stopImmediatePropagation(). The cafe order page has a real example: each dish button is also styled like a link, and clicking it should add the dish to the order without actually navigating away — that calls for preventDefault(), not stopPropagation(). Each method minds its own business, and using the wrong one leaves the job undone. Remember the rule: to stop propagation, use stopPropagation; to stop the default action, use preventDefault.
Step 9: Fire only once — once
Some buttons should only fire once, like “submit order”: one click submits, a second click would be a duplicate order. The once option is made for this: pass { once: true } and the listener is automatically removed when invoked. In MDN's example an outer container has one handler with once and one without; clicking the outer element shows the once message only the first time, while the ordinary message appears every time. The cafe order page uses once on the “submit order” button: one click submits once, a second click does nothing, and the order is never duplicated. One detail in another MDN example is worth copying: the callback is defined separately and hoisted outside, then passed to addEventListener, to prevent duplicate listeners from being attached — the same function reference is passed each time, so re-adding it does not mount a second copy. Remember the rule: for something that should happen only once, pass once: true and let the browser remove the listener for you.
Step 10: Keep scrolling smooth — passive
passive is made for events such as scrolling. The reasoning is this: if an event has a default action — a wheel event scrolls the container by default — the browser generally cannot start the default action until the event listener has finished, because it does not know in advance whether the listener might cancel the default action by calling preventDefault(). If the listener takes too long, the page stutters; MDN calls that delay jank. Setting passive to true declares that the listener will never call preventDefault(), so the browser can start the default action immediately, without waiting for the listener to finish. MDN's wheel example makes it concrete: a container with a long text, a listener that computes a million prime numbers — with passive on, the wheel scrolls at once; with it off, scrolling waits until the listener finishes. Two defaults are worth memorizing: for wheel, mousewheel, touchstart, and touchmove events on Window, Document, Document.documentElement, and Document.body, passive defaults to true; for other events and targets it defaults to false. To override that and make sure passive is false, you must set it explicitly rather than relying on the default. And a passive listener that calls preventDefault() gets nothing for it — nothing will happen, and a console warning may be generated. The cafe order page uses passive on the menu list's touchmove, so swiping the menu on a phone no longer stutters. Remember the rule: for a scroll listener that only watches and never blocks, pass passive: true.
Step 11: Remove a batch of listeners with one call — signal
Listeners that are attached eventually have to come off. MDN shows two ways. One is removeEventListener(), which needs the same function reference that was attached — an anonymous function leaves no reference behind, so it cannot be removed; the next section covers that in detail. The other is signal: pass an AbortSignal to addEventListener(), and when the abort() method of the AbortController that owns the signal is called, the listener is removed. In MDN's example a table has an abortable click listener that toggles the second cell's text between “two” and “three”; the moment the value reaches “three”, controller.abort() is called, and later clicks leave the text at “three” forever, because no code is listening for clicks anymore. The cafe order page uses signal for category switching: when the category changes, the old category's listeners are aborted as a batch first, then the new category's listeners are attached, leaving no stale listener behind to fire by mistake. Remember the rule: to remove listeners as a batch, manage them with one AbortController's signal.
Step 12: An anonymous function, once attached, cannot be taken off
This is a pitfall MDN gives its own section in the addEventListener() page. A listener only takes one argument, an Event, and its return value is ignored; to get data into and out of a listener, you need closures. More importantly, function references matter: attaching an anonymous arrow function to every element inside a loop creates a new function on each iteration — more memory, and no way to call removeEventListener() later, because no reference to the anonymous function is kept. Declare one named function, processEvent, and pass the same reference in the loop instead: only one handler function is created, and myElement.removeEventListener("click", processEvent, false) can remove it afterwards. The cafe order page used to attach anonymous functions inside a loop; when the menu switched categories, the old listeners could not be removed, so one click on a dish ran the order function twice, then three times, and the same dish showed up in the order several times. Defining the named function first and binding the same reference everywhere fixed it — on category switch the old listeners are removed cleanly by reference, and duplicate orders stopped. Remember the rule: for a listener you may need to remove later, give it a name and keep the reference before attaching it.
Step 13: Whose this is it — plain functions versus arrow functions
this inside a handler deserves attention too. MDN says: when a handler function is attached to an element using addEventListener(), the value of this inside the handler will be a reference to the element, the same as the value of the event's currentTarget property. In the example, a plain function on myElement logs this.className as myElement's class name, and e.currentTarget === this logs true. Arrow functions do not have their own this context: the same code as an arrow function makes this not myElement, and e.currentTarget === this logs false. There are two ways around it: use bind() to fix this in place, or pass an object with a handleEvent() method, so that this inside handleEvent points at that object itself. The cafe order page has a class that manages the whole order list, and its methods need to read this.orderList; passing a method straight in as a listener turned this into the button, and the order list could not be read. Wrapping it in an arrow function that calls this.addItem() kept this on the class, and the problem went away. Remember the rule: if this should be the element, use a plain function; if this should be the object outside, use an arrow function or bind.
Step 14: Passing a parameter to a listener — closures
The last piece is passing parameters. A listener only receives one event object, and its return value is ignored, so parameters cannot be passed and results cannot be returned the way ordinary functions do. MDN's answer is closures: the functions passed as event listeners have access to all variables declared in the outer scopes that contain the function. In the docs' example, an arrow function on a button reads an outer variable, someString: the first click logs “Data”, the second logs “Data Again”, because the outer variable has been changed. Another example wraps the call in an anonymous function: the listener itself is anonymous, and inside it modifyText("four") is called, so the parameter gets in that way. The cafe order page passes dish ids to its “add” buttons the same way: when binding listeners in a loop, a closure captures each dish's id, so clicking a dish gives the handler exactly that dish's id. Remember the rule: listeners take no parameters, so parameters ride in through closures.
Checklist: run through this list when your delegation is written
The chart below shows the causes of 80 click-handling incidents in one month on the fictional Greenstone Cafe order page: one listener per button, and new dishes did nothing when clicked, 24 times (30.0%); the wrong currentTarget, treating the container as the button, 18 times (22.5%); the click landed on the small icon inside the button, so target was not the button, 14 times (17.5%); a nested card, one click triggering two places through bubbling, 10 times (12.5%); anonymous functions attached and never removed, causing duplicate orders, 8 times (10.0%); a scroll listener without passive, making the page stutter, 6 times (7.5%). 24 + 18 + 14 + 10 + 8 + 6 = 80, and the percentages add up to 100.0%. The numbers are invented examples; the lessons are real, and the largest category is exactly the problem delegation exists to solve — wiring listeners one by one. When your own delegation is written, run through this list: is there only one listener, on the parent; are you reading target or currentTarget, and did you mix them up; when the click lands on an icon inside the button, is there a closest() safety net and a matches() identity check; do you need stopPropagation() to stop the bubbling; are you stopping propagation or the default action, and did you pick the right method; did the fire-once buttons get once; did the scrolling ones get passive; for listeners you will remove later, did you keep the function reference; is this the one you want; and did the parameters ride in through closures. When all ten pass, the delegation is done.
Comments (0)
Sources
Related articles
You already call functions every day; this guide names what you have been doing. Following MDN's Functions, Arrow function expressions, and Rest parameters: declarations versus expressions, parameters and arguments, default values, rest parameters, spread syntax, return values, arrow function shorthand, the this trap, callbacks, and scope.
One page should stand up on a phone, a tablet, and a computer. This guide follows MDN's Responsive web design, Using media queries, and the viewport meta reference: fluid HTML, the viewport tag, fluid grids and max-width, images that never burst their container, media query syntax, breakpoints set by content, mobile first, responsive type, testing capability instead of width, and a pre-launch checklist.
Numbers in JavaScript are one type, Number, stored as 64-bit floats — which is why 0.1 + 0.2 is 0.30000000000000004. This guide follows MDN's Basic math in JavaScript, Math, and Number: one number type, float error, counting money in cents, converting strings, NaN and Infinity, safe integers, the four rounding methods, Math.random, the Math toolbox, and formatting for display.