Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to have a variable not reset when refreshing my website

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading