Syncing account progress…

Back

Intermediate · 12 min

Respond to clicks

Register an event listener and update the page from application state.

Starting HTML

<button id="add" type="button">Add one</button>
<p id="count">0</p>

Register a handler

addEventListener() registers a function to run when an event occurs. Pass the function itself. Calling it while registering would run it immediately.

const button = document.querySelector("#add");
button.addEventListener("click", () => { document.querySelector("#count").textContent = "1"; });
button.click();
console.log(document.querySelector("#count").textContent);

Output

1

Keep state outside the handler

A counter must survive between clicks. Declare it outside the listener, then update the visible text after each change.

let count = 0;
const button = document.querySelector("#add");
button.addEventListener("click", () => {
  count += 1;
  document.querySelector("#count").textContent = String(count);
});
button.click();
button.click();
console.log(count);

Output

2

Put it into practice

  1. Predict each result before running the example.
  2. Complete the coding task, then explain why your solution works.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Make a working counter

Make each click add exactly 1 to count and update the page. The solution check clicks the button twice.

Page preview

Run your code, then try the controls below. Check solution resets the page and tries the actions described in the task.

Practice