Last active
August 29, 2015 14:16
-
-
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.
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
// 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