Skip to content

Counter

Beginner~10 min

What you'll build

A small HTML page with a number display and three buttons (+, −, Reset). Clicking a button updates the number on the page using JavaScript.

Goals

  • Select DOM elements with getElementById
  • Attach click handlers with addEventListener
  • Update an element's text content from JS
  • Keep application state in a variable

Prerequisites

  • Variables and assignment
  • Functions
  • Basic HTML structure

Steps

  1. 1

    Write the HTML

    Create counter.html with a span for the count and three buttons. Give each element an id so JavaScript can find it.

    Code
    <span id="count">0</span>
    <button id="inc">+</button>
    <button id="dec">−</button>
    <button id="reset">Reset</button>

    Expected result

    A number 0 and three buttons appear on the page.

  2. 2

    Select the elements and set up state

    In a script tag, select each element by id and declare a count variable starting at 0. State lives in JS; the DOM just displays it.

    Code
    const countEl = document.getElementById("count");
    const incBtn = document.getElementById("inc");
    const decBtn = document.getElementById("dec");
    const resetBtn = document.getElementById("reset");
    let count = 0;

    Expected result

    No visible change yet, but JS now has references to every element.

  3. 3

    Wire the increment button

    Add a click listener to the + button. Inside, increment count and set countEl.textContent to the new value. This is the core update pattern: change state, then render.

    Code
    incBtn.addEventListener("click", () => {
      count++;
      countEl.textContent = count;
    });

    Expected result

    Clicking + increases the displayed number by 1 each time.

  4. 4

    Wire decrement and reset

    Add listeners for the other two buttons. Decrement subtracts 1; reset sets count back to 0. Always update textContent after changing state.

    Code
    decBtn.addEventListener("click", () => {
      count--;
      countEl.textContent = count;
    });
    resetBtn.addEventListener("click", () => {
      count = 0;
      countEl.textContent = count;
    });

    Expected result

    − decreases the number; Reset returns it to 0.

Try it yourself

What you learned

You practiced the fundamental DOM pattern: select elements, keep state in a variable, listen for events, and update the DOM after each state change.

Related Resources

Related Lessons

  • DOM

    addEventListener and click handlers used in this project.

  • Variables

    The count variable that holds the application state.

Related Practice

Related Tools

Related Cheatsheets

Related Reference

Related Errors

Related Glossary

Related Glossary

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

Related Errors

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

← Back to topic