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