Created
March 11, 2014 15:59
-
-
Save bcole808/9488803 to your computer and use it in GitHub Desktop.
Animate a number inside of an element from one number to another; makes numbers look like they are counting up or down really fast!
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
/*************************************************** | |
* Takes a jQuery element $elem and animates the inner HTML if it is a number. | |
* Counts up to 'final_num' from 'start_num' over 'duration' milliseconds. | |
***************************************************/ | |
animateSingleNumber : function($elem, final_num, start_num, duration) { | |
var original_num = $elem.html(); | |
// If not set, take inner HTML of elem | |
if (!final_num) final_num = parseFloat($elem.html().replace(/,/,'')); | |
// If not set, count up from zero | |
if (!start_num) start_num = 0; | |
// If no set, default duration | |
if (!duration) duration = 1000; | |
// Find number of decimal places | |
var decimalPlaces = (Math.floor(final_num) !== final_num) ? final_num.toString().split(".")[1].length || 0 : 0; | |
// Test for correct EN locale string conversion | |
var goodLocaleStringSupport = (new Number(10).toLocaleString() == '10'); | |
//Parking count animation | |
$({countNum: 0}) | |
.animate({countNum: final_num},{ | |
duration: duration, | |
easing: 'swing', | |
step: function() { | |
// Round to decimal places | |
var stepNum = this.countNum.toFixed(decimalPlaces); | |
// Add a comma if not a decimal | |
if (decimalPlaces == 0 && goodLocaleStringSupport) stepNum = parseInt(stepNum).toLocaleString('en'); | |
$elem.html(stepNum); | |
}, | |
complete:function() { | |
$elem.html(original_num); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment