Skip to content

Instantly share code, notes, and snippets.

@getneerajk
Created February 16, 2024 09:06
Show Gist options
  • Save getneerajk/5cb6bd2ffa0f70bdee126002ccaf5767 to your computer and use it in GitHub Desktop.
Save getneerajk/5cb6bd2ffa0f70bdee126002ccaf5767 to your computer and use it in GitHub Desktop.
Animate numbers count #animation #count #js
document.addEventListener("DOMContentLoaded", function() {
/* animate counter
* <span class="animate-count">1000</span>
*/
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return rect.bottom > 0 &&
rect.right > 0 &&
rect.left < (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */ &&
rect.top < (window.innerHeight || document.documentElement.clientHeight) /* or $(window).height() */;
}
function animateCounter(element, countTo, duration) {
var start = 0;
var startTime = null;
function step(time) {
if (!startTime) startTime = time;
var progress = time - startTime;
var percentage = Math.min(progress / duration, 1);
element.innerText = Math.floor(percentage * countTo);
if (percentage < 1) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
}
window.addEventListener('scroll', function() {
var countItem = document.querySelectorAll('.animate-count');
if(countItem.length >= 0){
countItem.forEach(function(item) {
if (isElementInViewport(item) && !item.classList.contains('counted')) {
var countTo = parseInt(item.innerText);
item.innerText=0;
console.log(countTo);
item.classList.add('counted');
animateCounter(item, countTo, 1500);
}
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment