Created
July 24, 2011 02:19
-
-
Save timothyclifford/1102121 to your computer and use it in GitHub Desktop.
Javascript number counter animation
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
// Instantiate global variable to house timeout object | |
var animationTimeout; | |
function recalculateDiscount() { | |
// Get previous discount | |
var previousDiscount = parseInt(totalDiscount); | |
// Get current discount | |
totalDiscount = parseInt(calculateDiscount()); | |
// If previous and current differ, update | |
if (previousDiscount != totalDiscount) { | |
// Clear any existing animation | |
clearTimeout(animationTimeout); | |
// Update with new value | |
updateDiscount(totalDiscount); | |
} | |
} | |
function updateDiscount(newValue) { | |
// Get current value from HTML | |
var currentValue = parseInt($(".totalSavingsHeader").html().replace("$", "")); | |
// If current value matches new value, exit and clear animation | |
if (parseInt(currentValue) === parseInt(newValue)) { | |
clearTimeout(animationTimeout); | |
return; | |
} | |
// Work out whether to increase or decrease | |
var direction = (currentValue < newValue) ? "up" : "down"; | |
// Get new value | |
var htmlValue = direction === "up" ? (currentValue + 1) : (currentValue - 1); | |
// Update HTML with new value | |
$(".totalSavingsHeader").html("$" + htmlValue); | |
// Animate recursively | |
animationTimeout = setTimeout(function () { updateDiscount(newValue); }, 5); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment