JavaScript Count Button Clicks

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.

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.

How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color