A button click handler increments a counter and writes the new count into the page.

Program

Events let JavaScript react to user actions. The handler can update variables and the DOM together.

click_counter.html
Visuals: captured from real browser rendering
<button id="count">Add click</button>
<output id="total">0 clicks</output>
<script>
  let clicks = 0;
  const output = document.querySelector("#total");
  document.querySelector("#count").addEventListener("click", () => {
    clicks += 1;
    output.textContent = `${clicks} clicks`;
  });
</script>
  1. Initialize the click counter.

    The button and 0 clicks output are visible.
    The variable stores state outside the DOM.
  2. Register the click handler.

    The UI is unchanged while the click listener is attached.
    Adding a listener changes behavior, not pixels yet.
  3. Handle the first click.

    The output updates to 1 clicks.
    The handler increments state before writing output.
  4. Render the next click total.

    The output updates to 2 clicks.
    The DOM reflects the current variable value after another click.
event listener An event listener runs a function when a browser event occurs.
state variable A variable can hold interaction state between events.