Codeloft
0 0 XP

Respond to a click

8 min 20 XP + 10 for no hints

JavaScript can change a page while someone uses it. document.querySelector("#id") finds an element by its id.

addEventListener("click", ...) runs a function every time the element is clicked. Inside it, setting textContent replaces the element's text.

Click the button in the preview to test your code yourself. The checks also click it for you.

Example
<button id="btn">Clicked 0 times</button>
<script>
  let count = 0;
  const btn = document.querySelector("#btn");
  btn.addEventListener("click", () => {
    count++;
    btn.textContent = "Clicked " + count + " times";
  });
</script>
The code you want to run on click goes inside the curly braces of the arrow function: () => { … }.

Your tasks

0 of 2 done
  1. Use addEventListener to listen for a click
  2. Clicking the button changes the message text

Quick check

What does querySelector("#message") find?

click.htmlUpdates as you type