javascripthtmltumblr-html

How to make a JS counter permanently retain the number of counts?


I'm trying to make a page on my tumblr that has a button on it, which counts how many times it's been pressed. I've gotten it to work, but a browser close or refresh clears the value, and clicks from different people don't stack. Here's what I have:

<body>
  <div class="main">

    <h3>Click Counter</h3>
    <button id="clickme">Click me: 0</button>

    <h5>Filler Text</h5>

  </div>
  <script>
    var button = document.getElementById("clickme"),
        count = 0;
        
    button.onclick = function() {
      count += 1;
      button.innerHTML = "Click me: " + count;
    };
  </script>
</body>

This makes the button count up when pressed, but I want it to behave like so:

User #1 clicks twice. Counter reads two.

User #2 visits the page, counter is already at two, user clicks 3 times. Counter is at 5.

User #3 visits, counter is still at 5 for them as well, etc.

As of right now, each user visits the page and the value starts at zero. Help?


Solution

  • javascript runs on the browser and store all the variable in the browser so the scope of a variable is in the browser. you can use local storage but if all user uses the same browser which is not your need so only way to persist data is to save count (data) into the server and fetch count (data) on a load of the page.

    you can use firebase real-time database if you don't have any server.

    Getting started with Firebase real-time database for the web