Skip to content

Instantly share code, notes, and snippets.

@dniccum
Last active Aug 29, 2015
Embed
What would you like to do?
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