I am trying to create a click counter using HTML & JavaScript and I want to retain the value of the number after the page is refreshed.
I understand the fact that I have to use local storage for that and I have managed to store the value and display it after the page is refreshed but when I click on the button again, it starts the count from 0 and I do not know how to solve this issue. I want it to retain the value and continue counting even if the page is refreshed.
HTML Code:
<div>
<p id="display">0</p>
<button onclick="increase()">increase</button>
<button onclick="decrease()">decrease</button>
</div>
JavaScript Code:
let display=document.getElementById("display")
let count = 0
function increase(){
count=count+1
display.textContent=count
localStorage.setItem("count", JSON.stringify(count))
}
display.textContent=localStorage.getItem("count")
function decrease(){
count=count-1
display.textContent=count
}
let display=document.getElementById("display");
// Here was a mistake, you don't need to reset counter each time
let count = localStorage.getItem("count") ?
+localStorage.getItem("count") : 0;
function increase(){
count=count+1
display.textContent=count
localStorage.setItem("count", JSON.stringify(count))
}
display.textContent=localStorage.getItem("count")
function decrease(){
count=count-1
display.textContent=count
}
try above snippet.
let display=document.getElementById("display")
let count = Number(localStorage.getItem("count")) // here
function increase(){
count=count+1
display.textContent=count
localStorage.setItem("count", JSON.stringify(count))
}
display.textContent = count // and here
function decrease(){
count=count-1
display.textContent=count
}
I updated two lines of your code which is commented.
You have to set count variable first with value from localStorage.
when window load get the count value from local storage and init the count variable after that display that count value
const display = document.getElementById("display");
let count = 0;
window.onload = () => {
count = localStorage.getItem("count")
? JSON.parse(localStorage.getItem("count"))
: 0;
display.textContent = count;
};
function increase() {
count = count + 1;
display.textContent = count;
localStorage.setItem("count", JSON.stringify(count));
}
function decrease() {
count = count - 1;
display.textContent = count;
localStorage.setItem("count", JSON.stringify(count));
}