Created
September 9, 2016 13:32
-
-
Save bbrochier/d093643117320b81e2c546303e3e8edc to your computer and use it in GitHub Desktop.
Animate counter on scroll when visible
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
<div data-counter>1000</div> |
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
/* 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