Advertisement
ikai2

number counter with animation

Sep 19th, 2022 (edited)
577
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const counters = document.querySelectorAll('.counter');
  2. const speed = 400;
  3. counters.forEach(counter => {
  4.   const updateCount = () => {
  5.     const target = +counter.getAttribute('data-counter');
  6.     const count = +counter.innerText.replaceAll(',', '');
  7.     const inc = target / speed;
  8.     if (count < target) {
  9.       counter.innerText = Math.ceil(count + inc).toLocaleString('en-US');
  10.       setTimeout(updateCount, 1);
  11.     } else {
  12.       counter.innerText = target.toLocaleString('en-US');
  13.     }
  14.   };
  15.   const observeElement = function(elements) {
  16.     const element = elements[0];
  17.     if (element.isIntersecting) {
  18.       updateCount();
  19.       observer.unobserve(counter);
  20.     }
  21.   };
  22.   const observer = new IntersectionObserver(observeElement);
  23.   observer.observe(counter);
  24. });
  25.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement