Build a JavaScript Counter
In this project, you will learn how to build a counter using HTML, CSS and JavaScript. The counter will increase, decrease and reset its value when the user clicks buttons.
Project Introduction
A counter is one of the simplest JavaScript projects. It teaches an important programming concept: changing a value based on user interaction.
What You Will Learn
- HTML buttons
- JavaScript variables
- Functions
- Click events
- DOM manipulation
- Conditional statements
Create the HTML Structure
First, create a container for the counter. Inside it we need a number display and buttons.
<div class="counter">
<h2>
Counter
</h2>
<div id="count">
0
</div>
<button onclick="decrease()">
−
</button>
<button onclick="reset()">
Reset
</button>
<button onclick="increase()">
+
</button>
</div>
Create the Counter Display
The counter needs an element where the current number will be displayed.
<div id="count">
0
</div>
The ID count will allow JavaScript to find this element.
Create the Counter Buttons
We need three buttons: decrease, reset and increase.
<button onclick="decrease()">
−
</button>
<button onclick="resetCounter()">
Reset
</button>
<button onclick="increase()">
+
</button>
Create the Counter Variable
JavaScript needs a variable to remember the current counter value.
let count = 0;
The initial value is 0. Every button will change this value.
Create the Increase Function
To increase the counter, add 1 to the current value.
function increase(){
count++;
}
Same Logic Using +1
function increase(){
count = count + 1;
}
Create the Decrease Function
The decrease function subtracts 1 from the counter.
function decrease(){
count--;
}
You can also write:
count = count - 1;
Create the Reset Function
Reset should return the counter value to zero.
function resetCounter(){
count = 0;
}
Update the DOM
Changing the JavaScript variable alone does not automatically change the webpage. We need to update the HTML element.
const display =
document.getElementById("count");
display.textContent =
count;
Create an Update Function
function updateDisplay(){
display.textContent =
count;
}
Now call this function after increasing, decreasing or resetting the counter.
function increase(){
count++;
updateDisplay();
}
Add Value Limits
We can prevent the counter from going below zero by using an if statement.
function decrease(){
if(count > 0){
count--;
}
updateDisplay();
}
Maximum Value
We can also create a maximum value such as 100.
function increase(){
if(count < 100){
count++;
}
updateDisplay();
}
Complete Project Flow
Complete Counter Project
You have now learned how to create a JavaScript counter using variables, functions, events and DOM manipulation.
Tutorial Completed! 🔢
Now open the complete working Counter project and test what you have learned.
Run Complete Project Learn Increment & Decrement