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


Tracking button clicks is a common task in JavaScript and can be achieved by using the addEventListener() method. By adding an event handler method to the button element and incrementing a variable each time the button is pressed, we can simply keep track of button clicks. We can quickly show the user how many clicks there have been by showing that information on a web page and keeping the clicks in localStorage. We can even save the clicks even after the user shuts the browser.

Suppose we are building a simple calculator then we will need buttons that can do functions like addition, subtraction, multiplication, division, equal to, and so on. Hence, including a button on a web page is one approach to making it more interactive. In this blog, we will mainly see how to design a button and we will make it clickable and count the times it is clicked by the user.

Creating a Basic Button

We must first add a button element on our web page before we can begin tracking button clicks. The <button> HTML element is the simplest way to make a button on a web page.

Example 

<!DOCTYPE html>
<html>
<body>
   <button id="myButton">Click Me</button>
</body>
</html>

This creates a button with the text "Click Me" and an id of "myButton". We will use this id later to reference the button in our JavaScript code.

Tracking Button Clicks Using JavaScript

Method 1: addEventListener()

There are various JavaScript methods for monitoring button clicks, but the most common ways used today is to use the addEventListener() method. the addEventListener() function is an inbuilt javascript function which adds an event handler function to an element, this event handler runs when that certain event occurs such as, onclicking a button, hovering any element, element in, or element out. In our situation, we want to associate an event handler function with the button element, which will be executed when the button is clicked.

Example

Here is an example of how to use the addEventListener() method to track button clicks −

<!DOCTYPE html>
<html>
<body>
   <button id="myButton">Click Me</button>
   <p id="count"></p>
   <script>
      var count = 0;
      var button = document.getElementById("myButton");
      var countDisplay = document.getElementById("count");
      button.addEventListener("click", function() {
         count++;
         countDisplay.innerHTML = count;
      });
   </script>
</body>
</html>

First, select the Button element with the ID "myButton" using the getElementById() method. Then we will initialize the variable clickCount and set its value to zero. This clickCount variable is used to store and display the number of times the button is clicked.

The button element then receives the event handler code via the addEventListener() function. The first input to the addEventListener() method specifies the type of event to listen for (click in this example). The second parameter indicates the function to be performed when the button is pressed.

Increment the ClickCount variable in the event handler method and record the current value of ClickCount to the screen. This allows you to determine the frequency of button click.

Method 2: onclick()

This method attaches an event handler to the button element using the onclick property. The event handler function increments a counter variable each time the button is clicked.

Example

Here is the example code for onclick property

<!DOCTYPE html>
<html>
<body>
   <button id="myButton">Click Me</button>
   <p id="result"></p>
   <script>
      var count = 0;
      var button = document.getElementById("myButton");
      var result = document.getElementById("result");
      button.onclick = function() {
         count++;
         result.innerHTML = count;
      }
   </script>
</body>
</html>

Method 3: Using Bind Method

This method attaches an event listener to the button element using the bind method and also binds the current count value to the function.

Example

<!DOCTYPE html>
<html>
<body>
   <button id="myButton">Click Me</button>
   <p id="count"></p>
   <script>
      var count = 0;
      var button = document.getElementById("myButton");
      var countDisplay = document.getElementById("count");
      button.addEventListener("click", (function(count) {
         return function() {
            count++;
            countDisplay.innerHTML = count;
         }
      })(count));
   </script>
</body>
</html>

Method 4: Using a Closure

A closure is a function that can access variables in the parent function's scope even after the parent function has returned. You can maintain track of the count variable in a way that is not available from the global scope by using a closure.

Example

<!DOCTYPE html>
<html>
<body>
   <button id="myButton">Click Me</button>
   <p id="count"></p>
   <script>
      function createCounter() {
         let count = 0;
         return function() {
            count++;
            return count;
         }
      }
      const counter = createCounter();
      const button = document.getElementById("myButton");
      const countDisplay = document.getElementById("count");
      button.addEventListener("click", () => {
         countDisplay.innerHTML = counter();
      });
   </script>
</body>
</html>

Method 5: Storing the Click Count in Local Storage

While showing the click count on a web page is useful, it is not a long-term solution. The click count is lost whenever the user refreshes the page or shuts the browser. We can utilise the localStorage object to save the click count in the user's browser to save the click count even after the user shuts the browser.

Example

Here is an example of how to use localStorage to save the click count −

<!DOCTYPE html>
<html>
<body>
   <button id="my-button">Click Me</button>
   <div id="click-count">Button clicked: 0 times</div>
   <script>
      let button = document.getElementById("my-button");
      let clickCount = 0;
      let display = document.getElementById("click-count");
      if (localStorage.getItem("clickCount")) {
         clickCount = parseInt(localStorage.getItem("clickCount"));
      }
      button.addEventListener("click", function() {
         clickCount++;
         display.innerHTML = "Button clicked: " +  clickCount + " times";
         localStorage.setItem("clickCount", clickCount);
      });
   </script>
</body>
</html> 

First, we check if there is a value stored in localStorage under "clickCount". If there is a value stored on localStorage, then we parse it to an integer, and then assign it to the clickCount variable.

Next, add another line in the event listener function to save the current value of the clickCount variable to localStorage using the setItem() method. This way, even if the user refreshes the page or closes the browser, the clicks will be saved and retrieved the next time she visits her website.

It's important to note that the localStorage object has a storage limit of around 5-10MB depending on the browser. Also, the localStorage object stores the data as strings, so you need to convert the numbers to string and parse back to number when getting the values.

Updated on: 21-Feb-2023

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements