JavaScript Click Counter Example
hardJavaScript eventsHTML
A counter shows how a variable keeps its value between clicks.
The question
Create a button with id "add" and a <span id="count"> that starts at 0. Every click on the button must increase the count by 5.
The code
index.html
<button id="add">Add 5</button>
<p>Count: <span id="count">0</span></p>
<script>
var count = 0;
document.getElementById("add").addEventListener("click", function () {
count += 5;
document.getElementById("count").textContent = count;
});
</script>Result
How it works
- 1count is declared OUTSIDE the click function, so it is not reset on every click.
- 2Each click adds the step to count.
- 3textContent shows the new value in the #count span.
Common mistakes
- Declaring count inside the function — it starts from 0 on every click.
- Using innerHTML with user text (fine here, but textContent is the safer habit).
Now solve a similar question yourself
A new HTML / CSS / JS question every time, checked instantly.
