One Listener, Many Buttons

Apps are full of button groups: tabs, presets, modes. Give them all the same handler by looping over querySelectorAll, and tell them apart with data attributes. The usual "only one selected" pattern: when one is clicked, switch the class off on every button and on for the clicked one. classList.toggle(name, condition) does both in one line, adding the class when the condition is true and removing it when false.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

Every button got the same handler. Inside it, button is the one that was clicked, so toggle with the condition b === button switches selected on for that button and off for every other: exactly one is selected at a time.

YOUR TURN · WEB PAGE
Your turn → Add an input box for minutes. Make each preset button also put its number into the box, and make typing in the box remove the selected class from every preset, because a typed number is a custom choice.
loading editor…

Syntax has to be exact. Every quote, bracket, brace and parenthesis needs its partner, and every HTML tag you open needs closing. One slip and the script won't run; the message under the page will say where.

Event delegation puts one listener on the parent instead of one on every child. Clicks bubble up from the button to its parents, and event.target.closest("button") walks back up from whatever was clicked to find the button. It also works for buttons added after the page loaded.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

One listener on the list handles every button inside it. closest("button") finds the button that was clicked, or null when the click landed on the words, which the handler then ignores, and closest("li") finds that button's item.

◈ Graded Build

Clicking a mode button makes it the only button with the class active. Focus also sets #minutes to 25, Rest sets it to 5, and Custom leaves the number alone.

Checked by using your page: clicking, typing and waiting, then reading what changed. 3 visible and 1 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back