Skip to content

Instantly share code, notes, and snippets.

@dniccum
Last active August 29, 2015 14:16
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 dniccum/8c5a69420f9a47fcc854 to your computer and use it in GitHub Desktop.
Save dniccum/8c5a69420f9a47fcc854 to your computer and use it in GitHub Desktop.
A basic jQuery/Javascript counter to counts up to a certain number within a certain time period.
// target: The jQuery/Javascript element that you want the function to affect
// targetNumber: The max number you want the counter to get to
// type: Type of units the function outputs; can be modifed
// currentNumber: The number you would like to start from; leave undefined to start from zero
function countUp(target, targetNumber, type, currentNumber) {
var integer,
interval = (3 / targetNumber) * 1000; // 3 is the amount of time to give the counter to reach its desired amount
if (currentNumber === undefined) {
integer = 0;
} else {
integer = currentNumber;
}
if (integer !== targetNumber) {
setTimeout(function() {
if (interval <= 50) {
integer = integer + 2;
} else {
integer = integer + 1;
}
if (type === 'percent') {
target.html(integer + '%');
} else if (type === 'dollars') {
target.html('$' + integer);
}
countUp(target, targetNumber, type, integer);
}, interval);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment