How to count the number of times a button is clicked using JavaScript ?
We have given a button, and the task is to count how many times the button is clicked using JavaScript.
Approach: First, we will create a HTML button and a paragraph element where we display the button click count. When the button is clicked, the JavaScript function called. We declare a count variable and initialize it to 0. When user clicks the button, the count value increased by 1 and display it on the screen.
Example:
HTML
<!DOCTYPE HTML><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Increment count when button is clicked</title></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h4> How to count the number of times a button is clicked? </h4> <button id="btn">Click Here!</button> <p> Button Clicked <span id="display">0</span> Times </p> <script type="text/javascript"> var count = 0; var btn = document.getElementById("btn"); var disp = document.getElementById("display"); btn.onclick = function () { count++; disp.innerHTML = count; } </script></body> </html> |
Output:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!


