Skip to content

Instantly share code, notes, and snippets.

@RodrigoDornelles
Created December 28, 2021 17:43
Show Gist options
  • Save RodrigoDornelles/7bacd617a413023040387abc10946ebf to your computer and use it in GitHub Desktop.
Save RodrigoDornelles/7bacd617a413023040387abc10946ebf to your computer and use it in GitHub Desktop.
Increment animation when scroll to number
document.addEventListener("DOMContentLoaded", () => {
const elements = document.querySelectorAll('.animate-number');
const lerp = (start, end, amt) => Math.round((1-amt)*start+amt*end);
const interval = 10;
const amount = 0.03;
const increment = (el) => {
el.setAttribute('data-now', lerp(el.getAttribute('data-now'), el.getAttribute('data-end'), amount));
el.innerText = Number(el.getAttribute('data-now')).toLocaleString();
if (el.getAttribute('data-now') != el.getAttribute('data-end')) {
setTimeout(increment, interval, el);
}
};
document.addEventListener('scroll', () => {
Array.from(elements)
.filter((el) => !el.hasAttribute('data-end'))
.filter((el) => window.scrollY > (el.offsetTop - window.innerHeight))
.forEach((el) => {
el.setAttribute('data-end', el.innerText);
el.setAttribute('data-now', 0);
el.innerText = 0;
setTimeout(increment, interval, el);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment