Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CountUp no reset when user refresh page using localStorage

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading