Created
February 23, 2018 23:21
-
-
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)
This file contains 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
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