Skip to content

Instantly share code, notes, and snippets.

@lukemeyer
Created March 18, 2014 13:55
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 lukemeyer/9620533 to your computer and use it in GitHub Desktop.
Save lukemeyer/9620533 to your computer and use it in GitHub Desktop.
function animateNumber(element, endValue, endTime){
var now = new Date().getTime(),
timeLeft = endTime - now;
if ( timeLeft > 0 ){
//element must be a jQuery object
var isInput = element.is('input'),
currentValue = isInput ? parseInt(element.val().replace(',','')) : parseInt(element.html().replace(',','')),
newValue = currentValue,
done = false,
interval = 25;
if ( isNumber(currentValue) ) {
var diff = Math.abs( endValue - currentValue ),
increment = 1000,
thou = diff.toString().slice(-4,-3);
hund = diff.toString().slice(-3,-2);
ten = diff.toString().slice(-2,-1);
one = diff.toString().slice(-1),
steps = thou + hund + ten + one,
interval = timeLeft / steps;
if ( diff < 10 ) {
increment = 1;
} else if ( diff < 100 ) {
increment = 10;
} else if ( diff < 1000 ) {
increment = 100;
}
if ( currentValue < endValue ) {
//counting up
if ( currentValue + increment >= endValue ) {
//at or close to end
newValue = endValue;
done = true;
} else {
newValue += increment;
}
} else if ( currentValue > endValue ) {
//counting down
if ( currentValue + increment <= endValue ) {
//at or close to end
newValue = endValue;
done = true;
} else {
newValue -= increment;
}
}
} else {
//couldn't parse existing text as number just set the end value
newValue = endValue;
done = true;
}
} else {
//time's up just set the end value
newValue = endValue;
done = true;
}
//set new value
if ( isInput ){
element.val(numberWithCommas(newValue));
} else {
element.html(numberWithCommas(newValue));
}
if ( !done ) {
setTimeout( function() { animateNumber(element, endValue, endTime) }, interval);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment