Skip to content

Instantly share code, notes, and snippets.

@timothyclifford
Created July 24, 2011 02:19
Show Gist options
  • Save timothyclifford/1102121 to your computer and use it in GitHub Desktop.
Save timothyclifford/1102121 to your computer and use it in GitHub Desktop.
Javascript number counter animation
// 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