Home > Net >  Increment a counter every time the page refreshes
Increment a counter every time the page refreshes

Time:12-06

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 ?

CodePudding user response:

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>

CodePudding user response:

The first thing you're doing on page load is increment an undefined variable count to 1, then storing that in localStorage incCount. So that will always be 1.

Instead, you need to read the existing value first and increment that. (Here I use || 0 to handle the case where no localStorage yet exists):

var count;
function myFunction() { // you should probably use a better name here
  const previousCount = Number(localStorage.getItem("incCount")) || 0;
  count = previousCount   1;
  localStorage.setItem("incCount",count);
}

I've omitted the index variable here because I'm really not clear what you were trying to do with that, or if it's related to the given question; to just keep an incrementing count you only need the one variable.

CodePudding user response:

To increment a count on page refresh all you have to do is to first check whether there is already a value for that incCount key or not.

If it is not then you have to create a localStorage key-value and if it is already there then you just have to set incremented value.

<!DOCTYPE html>
<html>

<body onload="myFunction()">
  <h1>Hello World!</h1>
  <script>
    let count = 0; // change

    function myFunction() {
      const valueInLS = localStorage.getItem("incCount");
      alert(valueInLS);
      if (valueInLS) count = valueInLS;
      localStorage.setItem("incCount",   count);
    }
  </script>

</body>

</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You will have to use the onbeforeunload event. https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

  • Related