Skip to content

Instantly share code, notes, and snippets.

@DmitriyRF
Last active February 27, 2019 22:08
Show Gist options
  • Save DmitriyRF/17942bc25f281c1df2a84b6d9a5a5206 to your computer and use it in GitHub Desktop.
Save DmitriyRF/17942bc25f281c1df2a84b6d9a5a5206 to your computer and use it in GitHub Desktop.
Counter number for page when element gets visible
<script>
var DURATION = 3500;
var elementClassName = 'countUp';
function countEventFunc(event) {
var start = Date.now();
this.step = function () {
var progress = Date.now() - start;
this.innerHTML = Math.round(this.countNumber * progress / DURATION) + this.units;
if (progress < DURATION) {
window.requestAnimationFrame(this.step.bind(this));
}else{
this.removeEventListener('counting', countEventFunc);
}
}
window.requestAnimationFrame(this.step.bind(this));
}
var event = new Event("counting", {bubbles: false, cancelable: true});
function handleScroll(e) {
if( (screen.availHeight * 0.75) > this.getBoundingClientRect().top && !this.conunted ){
this.dispatchEvent(event);
this.conunted = true;
}
}
var counterElements =document.getElementsByClassName(elementClassName);
Array.prototype.forEach.call( counterElements, function setCounter(element){
var elemetContent = element.innerHTML;
var countNumber = parseFloat(elemetContent);
element.countNumber = countNumber;
var units = elemetContent.replace(countNumber,'');
element.units = units;
element.innerHTML = 0 + units;
element.addEventListener('counting', countEventFunc);
window.addEventListener('scroll', handleScroll.bind(element));
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment