Skip to content

Instantly share code, notes, and snippets.

@vibrates09
Last active February 22, 2022 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vibrates09/b7233f8d5458790bf5753f77d311df6d to your computer and use it in GitHub Desktop.
Save vibrates09/b7233f8d5458790bf5753f77d311df6d to your computer and use it in GitHub Desktop.
var statsCounter=document.querySelectorAll(".jsStatsCounter");function isInViewport(t){var e=t.getBoundingClientRect();return e.top>=0&&e.left>=0&&e.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&e.right<=(window.innerWidth||document.documentElement.clientWidth)}statsCounter.forEach(t=>{var e=!1;window.addEventListener("scroll",()=>{if(!e){var n=parseInt(t.dataset.start),o=parseInt(t.dataset.end),r=n;t.textContent=n,isInViewport(t)&&(e=!0,setInterval(()=>{r<o?r+=1:r=o,t.textContent=r},25))}},!1)});
@vibrates09
Copy link
Author

vibrates09 commented Feb 22, 2022

Unminified version

<p data-start="0" data-end="100" class="jsStatsCounter"></p>
const statsCounter = document.querySelectorAll(".jsStatsCounter");

statsCounter.forEach((item) =>{
  var started = false;

  window.addEventListener('scroll', () => {
    if (!started) {
      var start = parseInt(item.dataset.start)
      var end = parseInt(item.dataset.end)
      var counter = start
      item.textContent = start

      if (isInViewport(item)) {
        started = true
        setInterval(() => {
          if (counter < end) {
            counter += 1
          } else {
            counter = end
          }

          item.textContent = counter
        }, 25)
      }
    }
  })
})

function isInViewport (elem) {
  var distance = elem.getBoundingClientRect();
  return (
    distance.top >= 0 &&
    distance.left >= 0 &&
    distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    distance.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment