Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

384
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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



EDIT: COUNT IN BACKGROUND

This is not an 'actual' counting in the background. The idea here is to differentiate between the latest and last timestamp.

1. Change your var x line to:
var x = getCounter();
2. Add a new function. getCounter():
function getCounter() {
  if(localStorage.getItem('lastCount')) {
    let counter = (Math.floor(Date.now() /1000) - parseInt(localStorage.getItem('lastTimestamp'))) + parseInt(localStorage.getItem('lastCount'));
    return (counter > 100) ? 100: counter 
  } 
  return 1;
}

Note: The counter will not exceed 100. data-to="100"

3. Append this code to addNum():
localStorage.setItem('lastCount', x);
localStorage.setItem('lastTimestamp', Math.floor(Date.now() / 1000));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda