Last active
December 17, 2018 04:16
-
-
Save joshuacerbito/39c9734739c54754931ad0027b9948f9 to your computer and use it in GitHub Desktop.
Little script to animate numeric values
This file contains hidden or 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
/** | |
* 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