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

Increment a counter every time the page refreshes

How to increment and save counter value on page refresh ?

<!DOCTYPE html>
<html>
<body onload="myFunction()">
<h1>Hello World!</h1>
<script>

var count;
var index;
function myFunction() {
count++;
alert("after count++"+count);
localStorage.setItem("incCount",count);


alert("index here :"+index);
if(index==1){
var s=localStorage.getItem("incCount");
alert("s is"+s)
}
index++;

localStorage.setItem("incIndex",index);
var g=localStorage.getItem("incIndex");
alert("g is "+g)


alert("index after index++"+index)

  alert("Page is loaded");
}
</script>

</body>
</html>
    

I want to increase the count variable value by 1 , every time I refresh the page .But , its not working as per my expectation , what should I do ?

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 :

Read the count from local storage, convert it to a number using the Number function, and increment it while storing.

<!DOCTYPE html>
<html>

<body onload="myFunction()">
  <h1>Hello World!</h1>

  <script>
    function myFunction() {
      let count = Number(localStorage.getItem('count')) || 0;
      alert(`count ${count}`);
      localStorage.setItem('count', count + 1);
    }
  </script>

</body>

</html>
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