A click counter

Make two buttons control a number on the page.

What to build

A counter that goes up with one button, and goes back to zero with another.

Requirements

  • Clicking #more adds 1 to the number shown in #count.
  • Clicking #reset sets it back to 0.
  • Counting carries on correctly after a reset.

Constraints

Use addEventListener. Do not put onclick in the HTML.

Example

After three clicks on #more, #count shows 3.

Why it works

The variable outlives each click, because the handlers are closures that keep it alive. Keeping the number in a variable, rather than reading it from the page, means the data is always a real number.

Hints

Hint 1

Keep the count in a variable declared outside the handlers.

Hint 2

addEventListener("click", ...) on each button.

Hint 3

Set the paragraph's textContent after every change.

Solution

Show one correct solution (try it yourself first)
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Counter</title>
</head>
<body>
  <button id="more">Add one</button>
  <button id="reset">Reset</button>
  <p id="count">0</p>
  <script>
    const shown = document.querySelector("#count");
    let count = 0;

    function show() {
      shown.textContent = count;
    }

    document.querySelector("#more").addEventListener("click", () => {
      count++;
      show();
    });

    document.querySelector("#reset").addEventListener("click", () => {
      count = 0;
      show();
    });
  </script>
</body>
</html>

Lesson: Events and forms →