I have a CountUp script which i have specified the number it should start from and where it should stop counting. This works fine, however i have tried to use localStorage.setItem to save the progress so that when user refreshes the page or leaves the page and returns, the counter doesn’t refresh but keeps running. It doesn’t seem to work for me, admittedly i am still trying to struggle with Javascript being a newbie. Your help will be highly appreciated, thanks. Below is my Code
<script type="text/javascript">
function countUp() {
var countEl = document.querySelector('.counter');
var countBar = document.querySelector('.progress-bar');
var x = 1;
var y = countEl.dataset.to;
var z = countBar.dataset.to;
function addNum() {
countEl.innerHTML = x;
x += 1;
if (x > y && x > z) {
clearInterval(timer);
toggleBtn.classList.remove('hidden');
}
}
var timer = window.setInterval(addNum, 800);
localStorage.setItem("addNum", counter);
toggleBtn.addEventListener('click', function(){
countUp();
toggleBtn.classList.add('hidden');
});
}
countUp();</script>
<script src="//code.jquery.com/jquery-latest.min.js"></script></head>
<body onload=countUp();>
<div class="counter" data-from="0" data-to="100"></div>
<div class="progress-bar" data-from="0" data-to="100"></div>
Thanks in anticipation of a right pointer.
>Solution :
Change your var x line to:
var x = parseInt(localStorage.getItem('lastCount')) - 1 || 1;
Change addNum() function to:
function addNum() {
countEl.innerHTML = x;
x += 1;
if (x > y && x > z) {
clearInterval(timer);
toggleBtn.classList.remove('hidden');
}
localStorage.setItem('lastCount', x);
}
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage