Skip to content
Related Articles
Open in App
Not now

Related Articles

How to count the number of times a button is clicked using JavaScript ?

Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 10 Jan, 2023
Improve Article
Save Article

In this article, we are given a button, and the task is to count how many times the button is clicked using JavaScript. 

Approach: First, we will create an HTML button and a paragraph element where we display the button click count. When the button is clicked, the JavaScript function is called. We declare a count variable and initialize it to 0. When the user clicks the button, the count value increased by 1 and displays on the screen.

Example: This example shows the number of times a button is clicked.

HTML




<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="Content-Type" 
          content="text/html; charset=utf-8">
    <title>
      Increment count when button is clicked
    </title>
    <script>
      <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>
</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>
</body>
</html>

Output:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!