This tutorial will demonstrate the procedure for creating a simple counter with a click in JavaScript.
How to Create a Simple Click Counter Using JavaScript?
A click counter counts each click and displays it on the screen. It increments the counter value by using the JavaScript “onclick” event and “count”, which will be incremented on every click.
Example 1: Creating Simple Counter
In this example, we will create a simple counter containing a button with the “onclick” event attached to it. It works in such a way that when the button is clicked, it will invoke the user-defined function named “counterFunc()”:
<label id="count"></label><br><br>
<button onclick="counterFunc()">Click</button>
Set the initial value of the “count” equals to 0:
The “counterFunc()” function will increment the count by one and print using the “innerHTML” property:
count++;
document.getElementById("count").innerHTML = count;
}
The corresponding output is given as follows:
Example 2: Count and Reset
Here, we will add one more functionality in the above counter that is a “Reset” button. We will attach “onclick” event with the button to invoke the JavaScript defined function “resetFunc()”:
In “resetFunc()”, set the count value to 0. When the “Reset” button is clicked, the counter turns to 0 as the reset value:
count=0;
document.getElementById("count").innerHTML = count;
}
The output signifies that we can easily reset the counter and start the counting again:
Example 3: After Refreshing Start From the Same Count
In websites, there are some situations where we need to start the count from the same existing count even after refreshing the page.
For this purpose, we will use the “localStorage” of the browser in our JavaScript defined function which will be called on the click on button where “onclick” event attached:
if (typeof(Storage) !== "undefined") {
if (localStorage.count) {
localStorage.count = Number(localStorage.count)+1;
} else {
localStorage.count = 1;
}
document.getElementById("count").innerHTML = localStorage.count;
}else {
document.getElementById("count").innerHTML = "Sorry, the browser you used does not support web storage.";
}
}
It can be seen that the output starts the count from the same, even after refreshing the page. This happens because of the “localStorage” property. This property enables the JavaScript apps and sites to save the key-value pair in the web browser without any expiration date:
We have compiled all the necessary instructions related to creating a simple click counter using JavaScript.
Conclusion
To create a simple click counter using JavaScript, you can use the JavaScript “onclick” event and a variable count whose value will be incremented on every click. You can also create a reset button on the counter to reset the count. Moreover, utilizing the “localStorage” property can assist in saving the counter value even after refreshing the page. This tutorial demonstrated the procedure for creating a counter on a click in JavaScript.