Created
March 18, 2014 13:55
-
-
Save lukemeyer/9620533 to your computer and use it in GitHub Desktop.
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
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