In this tutorial we will learn how to Count Button Clicks with JavaScript. We can use onclick event to trigger a JavaScript function on every click and inside this function we can count the number of clicks.
Table of Contents
onclick event
onclick event triggers the click event for HTML tag or it attaches the function execution with a click event.
In this example onclick event will execute a function which will count the total number of button clicks.
HTML Code
HTML Code is given below, in this code we have a button tag with onclick event and a paragraph tag to display the total count.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Count Button Clicks</title>
</head>
<body>
<button onclick="countClicks()">Click Me!</button>
<p id="output"></p>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, In this code user defined function countClicks() will count the total clicks.
The total count of clicks is saved inside a variable. The variable is initialized outside of main function with the value set to 0.
Then on each click of a button, 1 is added to the variable to increase the counter value.
getElementById() method is used with innerHTML property to display the total clicks as output.
<script>
var count = 0;
var output = document.getElementById('output');
function countClicks()
{
count = count + 1;
output.innerHTML = count;
}
</script>
You can also use JavaScript increment operator (++), to increase the counter value by 1.
<script>
var count = 0;
var output = document.getElementById('output');
function countClicks()
{
count++;
output.innerHTML = count;
}
</script>
Demo
Video Tutorial
Watch video tutorial on How To Count Button Clicks in JavaScript.