Skip to content

Instantly share code, notes, and snippets.

@bbrochier
Created September 9, 2016 13:32
Show Gist options
  • Save bbrochier/d093643117320b81e2c546303e3e8edc to your computer and use it in GitHub Desktop.
Save bbrochier/d093643117320b81e2c546303e3e8edc to your computer and use it in GitHub Desktop.
Animate counter on scroll when visible
<div data-counter>1000</div>
/* Trigger animation
========================================================================== */
if ($('[data-counter]').length) {
//For each counter in the page
$('[data-counter]').each(function() {
//check counter prosition to trigger animation when visible
var $currentCounter = $(this);
var isTriggered = false;
var sy = $(window).scrollTop();
var iCounterOffset = $currentCounter.offset().top;
var iWindowHeight = $(window).height();
//trigger animation if already visible
if (sy >= (iCounterOffset - iWindowHeight) && isTriggered === false) {
isTriggered = true;
animateCounters();
}
//trigger animation on scroll
$(window).on('scroll', function() {
sy = $(window).scrollTop();
iCounterOffset = $currentCounter.offset().top;
iWindowHeight = $(window).height();
if (sy >= (iCounterOffset - iWindowHeight) && isTriggered === false) {
isTriggered = true;
animateCounters();
}
});
});
}
/* Counter animation
========================================================================== */
function animateCounters() {
var $counter = $('[data-counter]');
$counter.css({opacity: 1});
$counter.each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 3000,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment