Created
December 28, 2021 17:43
-
-
Save RodrigoDornelles/7bacd617a413023040387abc10946ebf to your computer and use it in GitHub Desktop.
Increment animation when scroll to number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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