Responding to Clicks

An event is a moment the browser tells you about: a click, a key press, a box being typed into. element.addEventListener("click", handler) says: when this happens to this element, run this function. The function is called a handler, and it runs every time the event happens, as often as it happens.

EXAMPLE · WEB PAGE
loading editor…
WHAT THIS DOES

addEventListener connected the click to addOne. Nothing happens until you click; then addOne runs, adds to the count variable and writes it onto the page. The variable is the app's memory, and the page only shows it.

YOUR TURN · WEB PAGE
Your turn → Add a Reset button with its own handler that sets count back to 0 and updates the page. Then add a third button that adds 10.
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.

✦ Hand over the function, don't call it

addEventListener("click", addOne()) runs addOne once, immediately, and hands over whatever it returned, which is undefined, so clicks then do nothing. Without the parentheses you hand over the function itself, to be run later, on each click.

Every handler receives an event object describing what happened. event.target is the element the event happened to, which matters when one handler serves several buttons.

◈ Graded Build

Make a counter that never goes below zero. The + button adds 1 and the − button subtracts 1, and #count always shows the current number. Pressing − at zero leaves it at zero.

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: Inputs, Forms and Keys →
← Back