Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

385
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda