JavaScript counter
A counter combines a variable, a click event, and a DOM update.
What you will learn
- How a click changes a variable
- How to display the new value
Minimal example
<button id="plus" type="button">+1</button> <span id="value">0</span> <script>let count = 0; plus.onclick = () => value.textContent = ++count;</script>Each click increases count, then writes the new value into the span.
Common mistakes
- Make sure the element IDs match the JavaScript selectors.
- Update the displayed value after changing the variable.
- Use a button for an action so it works with keyboard input.