Dark Zero
Dark Zero

Reputation: 5

How can I make a counter in HTML/CSS

So I made a button thats suppose to keep track of how many time ANYONE clicked, like a total click counter. But I encounter an issue where when I reload the page, it resets back to 0. I want to make sure that it will count everyones click and save

  <script>
    let num = 0;
    function myFunction() {
    document.getElementById("num").textContent = ++num;
  }
  </script>
  
  <button class="button" onclick="myFunction()">
  <p id="num"></p>

Upvotes: 0

Views: 2892

Answers (2)

Philipp
Philipp

Reputation: 69723

You can not do that with browser-based javascript alone. Your website is executed on the client and has no direct way to communicate with other clients. When you want to have any information in your client-sided javascript which is not available to the client (like who else is accessing the website), then you need to request that information from a server.

This means you need some form of server-sided programming to log and count page access, store the number on the server and embed that number in the HTML documents being delivered.

The technology options for server-sided web development are countless. Even just listing all the options you have would make this answer far too long. So I am not going to give you an example in any particular technology. Do your own research to get an overview of the technology options available to you and decide which one you would like to learn. When you are not sure how to do this in the technology you picked, feel free to ask a new question.

Upvotes: 2

frendy wijaya
frendy wijaya

Reputation: 77

you can save your current state into localstorage

like this

 <script>
    let num = localStorage.getItem("counter");
    function myFunction() {
    document.getElementById("num").textContent = ++num;
    localStorage.setItem("counter", document.getElementById("num").textContent);

  }
  </script>
  
  <button class="button" onclick="myFunction()">
  <p id="num"></p>

Upvotes: -1

Related Questions