Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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/

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!