addEventListener & state
React to clicks
Lesson 5 of 20 · 10 min · Module 2: Respond to people
Interactive pages respond to people: a click, a key press, a form being sent. You tell the browser which function to call when something happens, and keep track of what has changed.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Run code when something happens with addEventListener
- Keep state in variables
- Report toggle state with aria-pressed
The idea
element.addEventListener('click', handler) calls handler on every click. Keep the current state in variables, such as whether the post is liked and how many likes it has, and update the page from them. A toggle button reports its state with aria-pressed, so screen readers announce it as pressed or not pressed.
const button = document.querySelector('#more');
let clicks = 0;
button.addEventListener('click', () => {
clicks += 1;
button.textContent = `Clicked ${clicks} times`;
});
01Register once, react many times
addEventListener stores your function and calls it every time the event happens. The script itself runs only once, when the page loads.
02State first, page second
The variables are the truth; the page is a picture of them. Updating the variables and then the page in one place avoids the classic bug where the text says one thing and the counter another.
let liked = false;
// click: liked = !liked; then update every part of the page that depends on it
03Toggle buttons for everyone
aria-pressed tells assistive technology that the button is a toggle and whether it is on. The visible text and colour help sighted users; the attribute helps everyone else, and CSS can style [aria-pressed="true"] directly.
Your turn
#like is clicked, toggle the liked state. Liking sets aria-pressed="true", changes the button text to Liked and the counter from 12 likes to 13 likes; clicking again undoes all three. Keep the state in variables.What the checks look for
- One click likes the post
- A second click undoes it
- A third click likes it again
- Nothing changes before a click
Take this with you
Listen for events, update the state, then show the state on the page.
Go a little further
Disable the button for one second after each click to prevent accidental double clicks.