Respond to events
Make a button do something.
Wait for a moment
An event is a signal that something happened, such as a click. addEventListener attaches a function that runs when that event reaches the element.
Keep a little state
State is information your interface remembers. The count variable starts at zero. Each click increases it, then updates the visible text.
Use a native button
A button works with pointer and keyboard interaction. Attaching a click listener to it lets the browser handle those standard interactions. Keep the script after the markup so the element exists before you select it.
Try the example
<h1>Small steps add up.</h1>
<button type="button" id="step">Take a step</button>
<p id="count" aria-live="polite">0 steps taken.</p>
<script>
let count = 0;
document.querySelector("#step").addEventListener("click", () => {
count += 1;
document.querySelector("#count").textContent = `${count} steps taken.`;
});
</script>Enable JavaScript to edit and run the example in the playground.
Your turn
Change the increment to 2. Add a second button that resets count to zero and updates the paragraph.
Check your understanding
When does the event listener function run?
- Only when the script first loads
- When the matching event occurs
- Every second
Show answer and explanation
When the matching event occurs. The callback runs in response to the event it was registered for.