0

 <script>
 var sum = 0;
var pressYet = false;
function changeIt() {
   if(pressYet == false){
    sum++;
    document.getElementById('test').innerHTML = sum;
   pressYet = true;
   } else {
   
   document.getElementById('test').innerHTML = "You have already pressed the button";
 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>

SO I have this sweet epic button on my website, its very cool, but I want to make it better. I was wondering how to make the variable 'sum' not reset every time I refresh my website. I know there's a term for that but for the life of me I cannot figure it out. I want it so every time someone presses the button, 'sum' gets added one to it and that number would be permanent. So over time that number gets very large.

I am very new to HTML so please be kind to me.

  • Does this answer your question? [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) – showdev Apr 09 '22 at 19:27

1 Answers1

0

You can save the value to localStorage and then retrieve it from localStorage after page load. Then on the basis of the data you can adjust the page. I have slightly modified your code here

var sum = 0;
var pressYet = localStorage.getItem('pressYet');

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

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

}

(function init() {
  if (localStorage.getItem('pressYet') != null || localStorage.getItem('pressYet') != "") {
    document.getElementById('test').innerHTML = "You have already pressed the button";
    document.getElementById("button").style.visibility = "hidden";
  }
})();
<div id="test">
  <b> <var> Test </ var> </b>
</div>

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

You can check out the demo https://jsfiddle.net/5jyrk6s8/

Joy Dey
  • 563
  • 1
  • 5
  • 17
  • This is very cool and I will use it, but I was mainly wondering on how to make the sum variable go into local storage. I want for a person to click the button, it adds one to the sum (so I can check how many people pushed the button) and then they can't click it anymore. – Mother Thief Apr 09 '22 at 19:29
  • store the sum value in localStorage and then get the value from localstorage. Thats it – Joy Dey Apr 09 '22 at 19:32