Skip to content

Instantly share code, notes, and snippets.

@ben-heath
Created February 23, 2018 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ben-heath/d727d25c75c184040261f6d361143774 to your computer and use it in GitHub Desktop.
Save ben-heath/d727d25c75c184040261f6d361143774 to your computer and use it in GitHub Desktop.
Makes numbers animate from a number to another number (using IntersectionObserver API)
jQuery(document).ready(function(){
//jQuery('#rs-fullwidth-helper1').before('<p style="color:black;">testing4</p>');
function countUp() {
jQuery('.counter').each(function() {
var counter = jQuery(this),
countTo = counter.attr("data-count");
jQuery({ countNum: counter.text()}).animate({
countNum: countTo
},
{
duration: 3000,
easing:"swing",
step: function() {
counter.text(Math.floor(this.countNum));
},
complete: function() {
counter.text(this.countNum);
//alert("finished");
}
});
});
}
// Make sure to include the polyfill script for non-compatible browsers (IntersectionObserver)
// https://www.npmjs.com/package/intersection-observer#browser-support
const images = document.querySelectorAll('.counter');
observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
countUp();
} else {
var allCounters = document.querySelectorAll(".counter");
[].forEach.call(allCounters, function(allCounters) {
allCounters.innerHTML = "0";
});
}
});
});
images.forEach(image => {
observer.observe(image);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment