How to count the number of button clicks?

How do I permanently count the number of times a button was clicked for everyone on the website?
I have this but, it resets every time I went on it. So I want it to be permanent across the globe for all the users like someone click it then another user can view their click.

<button onclick="myFunction()">Click</button>
<p id="demo"></p>

var count = 0;
function myFunction() {
  document.getElementById("demo").innerHTML = count++;

Can you do this without databases though?

Well you need to persist the value. So you could use any medium for that which persists data. A database is usually the logical choice, but you could also write the value to file, put it in some kind of persistent storage system or cache etc.

Since JavaScript is typically client side, it is thrown away when they leave the page. So you need a way keep that value around. Usually a database is how this is done. Especially if you are wanting to keep track of everyone on the website.

1 Like

localStorage may be one way to store the incremented value in a loop.
Something like this:

Well like I was saying, that is client side right so if you are wanting to keep track of all users across the site, you need a server side counter. It is unclear from the OP if they were looking to just track the counts for an individual across a session, across multiple sessions and across multiple users.


You can write to and read from a simple text file by PHP or similar.