Skip to content

Instantly share code, notes, and snippets.

@raphaelchaib
Last active March 1, 2016 04:41
Show Gist options
  • Select an option

  • Save raphaelchaib/5ea8a7b8cbecb86c3444 to your computer and use it in GitHub Desktop.

Select an option

Save raphaelchaib/5ea8a7b8cbecb86c3444 to your computer and use it in GitHub Desktop.
JavaScript: Animate counter on document scroll
// statistics counter animation
var counterFx = function counterFx(element) {
var dfd = element.map(function(i, el) {
var data = parseInt(this.dataset.value.replace(/[\.,]+/g, ''));
var props = {
"from": {
"count": 0
},
"to": {
"count": data
}
};
return $(props.from).animate(props.to, {
duration: 1000 * 3,
step: function(now, counterFx) {
$(el).text(Math.ceil(now));
},
complete: function() {
if (el.dataset.sym !== undefined) {
el.textContent = el.textContent.concat(el.dataset.sym)
}
}
}).promise();
}).toArray();
// return jQuery promise when all animations complete
return $.when.apply($, dfd);
};
var counterFxReset = function counterFxReset(el) {
// do stuff when window `.scrollTop()` > el
$that = $(this);
console.log('scrollTop', $that.scrollTop());
$(el).each(function(i, v) {
console.log('v', $(v).offset().top);
console.log('scroll', ($that.scrollTop() + $that.height()));
if (($that.scrollTop() + $that.height()) > $(v).offset().top) {
// turn off scroll event so `counterFx` not called
// during ongoing animation
$that.off("scroll");
// when all animations complete
counterFx($(v));
}
})
};
// if `counterFx` should only be called once ,
// change `.on()` to `.one()` ,
// remove `.then()` callback following `counterFx()`
// within `counterFxReset`
$(window).on("scroll", function() {
counterFxReset($('.statistics .counter'))
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment