Skip to content

Instantly share code, notes, and snippets.

@sftsk
Created March 13, 2015 09:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sftsk/890bc60edd36a9998fb5 to your computer and use it in GitHub Desktop.
Save sftsk/890bc60edd36a9998fb5 to your computer and use it in GitHub Desktop.
small jQuery plugin to animate a counting to number
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
function updateTimer() {
var printValue;
value += increment;
loopCount++;
// if (value <= 9) {
// printValue = '0' + value.toFixed(options.decimals);
// } else {
printValue = value.toFixed(options.decimals);
// }
$(_this).html(printValue);
if (typeof(options.onUpdate) === 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) === 'function') {
options.onComplete.call(_this, value);
}
}
}
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment