How to add a button click counter with JavaScript?

Sometimes, we want to add a button click counter with JavaScript.

In this article, we’ll look at how to add a button click counter with JavaScript.

How to add a button click counter with JavaScript?

To add a button click counter with JavaScript, we can add a click handler to a button.

For instance, we write:

<button>Click me</button>
<p>Clicks: <span id="clicks">0</span></p>

to add a button and a clicks display element.

Then we write:

const button = document.querySelector('button')
const span = document.querySelector('span')

let clicks = 0;

button.onclick = () => {
  clicks += 1;
  span.innerHTML = clicks;
};

to select the button and the span with querySelector.

Next, we set button.onclick to a click event handler function.

In it, we increment clicks by 1.

And we set span.innerHTML to clicks.

As a result, when we click the button, we show the number of clicks.

Conclusion

To add a button click counter with JavaScript, we can add a click handler to a button.