Skip to content

Instantly share code, notes, and snippets.

@huttj
Created December 30, 2016 08:10
Show Gist options
  • Save huttj/01572d6b7187756ca406477773936e8d to your computer and use it in GitHub Desktop.
Save huttj/01572d6b7187756ca406477773936e8d to your computer and use it in GitHub Desktop.
$('[data-counter]').each(function(i, n) {
runCounter($(n));
});
function runCounter($el) {
var target = +$el.data('counter');
var step = +($el.data('step') || Math.floor(target / 711) + 2);
var commas = ''+$el.data('commas') === 'false' ? false : true;
var value = 0;
(function loop() {
var n = commas ? addCommas(''+value) : value.toFixed(2);
$el.text(n);
if (value < target) {
value = Math.min(value + step, target);
setTimeout(loop);
}
})();
}
function addCommas(n) {
var res = '';
for (var i = n.length - 1, run = 0; i >= 0; i--) {
if (run === 3) {
res = ',' + res;
run = 0;
}
res = n[i] + res;
run++;
}
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment