Skip to content

Instantly share code, notes, and snippets.

@joshuacerbito
Last active December 17, 2018 04:16
Show Gist options
  • Save joshuacerbito/39c9734739c54754931ad0027b9948f9 to your computer and use it in GitHub Desktop.
Save joshuacerbito/39c9734739c54754931ad0027b9948f9 to your computer and use it in GitHub Desktop.
Little script to animate numeric values
/**
* animateCount
*
* Usage:
* animateCount({
* selector: '.your-selector', // the selector for the element to animate
* from: 0, // the value to animate from
* to: 50, // the value to animate to
* duration: 1000 // animation duration in miliseconds, defaults to 1000
* })
*/
export const animateCount = ({
selector = null,
from = 0,
to = 0,
duration = 1000,
pad = false,
onEnd = null
}) => {
const obj = document.querySelector(selector);
const range = to - from;
let current = from;
let increment = to > from? 1 : -1;
let stepTime = Math.abs(Math.floor(duration / range));
function zeroPad(num, places) {
if(!!pad) {
const zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
}
const timer = setInterval(() => {
current += increment;
obj.innerHTML = zeroPad(current, 2);
if (current == to) {
clearInterval(timer);
if(typeof onEnd === 'function') {
onEnd.apply(this, arguments);
}
}
}, stepTime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment