As you see my Code below, When I reload the page, All my UI value changed. I want to get data from locale storage after loading the page. please help me to solve.
document.getElementById('btn-increase').addEventListener('click', ()=>{
const countNumber = document.getElementById('count');
const countStr = countNumber.innerText;
const counts = parseInt(countStr);
const countTotal = counts 1;
countNumber.innerText = countTotal;
// set in local storage
localStorage.setItem('count', countTotal);
});
const storage = ()=>{
localStorage.getItem('count');
}
storage();
CodePudding user response:
So set the element's text from local storage
const countNumber = document.getElementById('count');
document.getElementById('btn-increase').addEventListener('click', ()=>{
const countStr = countNumber.innerText;
const counts = parseInt(countStr);
const countTotal = counts 1;
countNumber.innerText = countTotal;
// set in local storage
localStorage.setItem('count', countTotal);
});
const storage = ()=>{
countNumber.innerText = localStorage.getItem('count') || 0;
}
storage();
How I would do it
const outputElem = document.getElementById('count');
let countTotal = Number(localStorage.getItem('count') || 0);
document.getElementById('btn-increase').addEventListener('click', ()=> {
countTotal ;
localStorage.setItem('count', countTotal);
updateOutput();
});
function updateOutput() {
outputElem.textContent = countTotal;
}
updateOutput();
CodePudding user response:
this way...
const
Bt_increase = document.querySelector('#btn-increase')
, Elm_counter = document.querySelector('#count')
;
// zero is initial value when localStorage count element doesn't exist
var count = parseInt((Storage.getItem('count') || '0'),10);
// set Counter value on page
Elm_counter.textContent = count
Bt_increase.onclick = evt =>
{
localStorage.setItem('count', count)
Elm_counter.textContent = count
}