Home > Mobile >  How to have a variable not reset when refreshing my website
How to have a variable not reset when refreshing my website

Time:04-10

 <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.

CodePudding user response:

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/

  • Related