How to Count Number of Clicks on an Element With Vanilla JavaScript

Counting the amount of clicks on an element is one of the easiest things you can do with JavaScript. All you need to do is to declare a variable to store your clicks and then use the addEventListener method on your target element. 

Let’s say you want to track the number of clicks on a button element, e.g. a home button. 

The HTML markup

Create an HTML button element and give it a class of button-home:

<button class="button-home">Home</button>

The JavaScript 

Add the following code to your JavaScript file (I’ll explain the code below):

let buttonHome = document.querySelector(".button-home");
let CountButtonHomeClicks = 0;

buttonHome.addEventListener("click", function() {
  CountButtonHomeClicks += 1;
  console.log(CountButtonHomeClicks);
});

The result:

Video showing the JavaScript console logging the number of total clicks

I added a bit of CSS styling to the button element above to make it easier to hit.

What’s happening in the JavaScript code:

  • First, we use the querySelector() method to select the button-home class on the button element. Then we assign it to the buttonHome variable.
  • Then we declare the CountButtonHomeClicks variable to store our future clicks. We give it a default initial value of 0.
  • Then we attach an event listener to our buttonHome by using the addEventListener() method.
  • Inside our event listener we specify that we’re listening for 'click' events and that we want to execute a function() on every click event.
  • Inside our function, we specify that want to add 1 to our CountButtonHomeClicks variable everytime the click event is triggered. To add 1, we use the += (plus equals) operator.
  • Finally, we log each click event using console.log() on our CountButtonHomeClicks variable.

Now you know how to count clicks on a specific element.

Good to know:

  • The code above is using ES6 syntax. If you’re using ES5, just replace let with var and it will work the same.
  • The function type we use in this example is called an anonymous function because it doesn’t have a name — unlike function expressions and function declarations.
  • Anonymous functions cannot be reused. If you need call the same function on several events, use a function expression or function declaration.

Get the code

Here’s a CodePen with all the code above.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on