Skip to content
Advertisement

How to make a dynamic value not a cookie

<script>
  var sum = localStorage.getItem('sum');
  var pressYet = localStorage.getItem('pressYet');

  function changeIt() {
    if (pressYet == null) {
      sum++;
   localStorage.setItem('sum', sum);
      document.getElementById('test').innerHTML = sum;
      pressYet = true;
     localStorage.setItem('pressYet', pressYet);
    } else {

      document.getElementById('test').innerHTML = "You have already pressed the button, " + sum;
      document.getElementById("button").style.visibility = "hidden";
   
    }

  }
   </script>
<div id="test">
   <b> <var> Test </ var> </b>
</div> 

<button onclick="changeIt()" id = "button" >Press If you are here</button>

HI. I am very new to both JavaScript and HTML. In my cool website I have this button. I want it to add 1+ to the var sum whenever someone presses it, so that it’ll become a huge number over time. But there is a problem. The var sum keeps resetting, and I think it has to do with the fact that I have it in local storage.

Is there is another storage type or a different way storing this var so that it doesn’t reset? I also want the var sum to be the same for all, so that everyone on my website sees the same sum value.

If someone can help me accomplish this it would make me really happy :).

Advertisement

Answer

You can do this by connecting it to the database like Mongo DB, Firebase etc., but what you want to accomplish would need an extra WebSocket connection because if I am updating a button and someone else is also updating it should also show the updates even if I am not reloading my web page.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement