(function ($) { var countto = function (element, options) { this.$element = $(element); this.options = $.extend({}, countto.defaults, this.dataoptions(), options); this.init(); }; countto.defaults = { from: 0, // the number the element should start at to: 0, // 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 formatter: formatter, // handler for formatting the value before rendering onupdate: null, // callback method for every time the element is updated oncomplete: null // callback method for when the element finishes updating }; countto.prototype.init = function () { this.value = this.options.from; this.loops = math.ceil(this.options.speed / this.options.refreshinterval); this.loopcount = 0; this.increment = (this.options.to - this.options.from) / this.loops; }; countto.prototype.dataoptions = function () { var options = { from: this.$element.data('from'), to: this.$element.data('to'), speed: this.$element.data('speed'), refreshinterval: this.$element.data('refresh-interval'), decimals: this.$element.data('decimals') }; var keys = object.keys(options); for (var i in keys) { var key = keys[i]; if (typeof(options[key]) === 'undefined') { delete options[key]; } } return options; }; countto.prototype.update = function () { this.value += this.increment; this.loopcount++; this.render(); if (typeof(this.options.onupdate) == 'function') { this.options.onupdate.call(this.$element, this.value); } if (this.loopcount >= this.loops) { clearinterval(this.interval); this.value = this.options.to; if (typeof(this.options.oncomplete) == 'function') { this.options.oncomplete.call(this.$element, this.value); } } }; countto.prototype.render = function () { var formattedvalue = this.options.formatter.call(this.$element, this.value, this.options); this.$element.text(formattedvalue); }; countto.prototype.restart = function () { this.stop(); this.init(); this.start(); }; countto.prototype.start = function () { this.stop(); this.render(); this.interval = setinterval(this.update.bind(this), this.options.refreshinterval); }; countto.prototype.stop = function () { if (this.interval) { clearinterval(this.interval); } }; countto.prototype.toggle = function () { if (this.interval) { this.stop(); } else { this.start(); } }; function formatter(value, options) { return value.tofixed(options.decimals); } $.fn.countto = function (option) { return this.each(function () { var $this = $(this); var data = $this.data('countto'); var init = !data || typeof(option) === 'object'; var options = typeof(option) === 'object' ? option : {}; var method = typeof(option) === 'string' ? option : 'start'; if (init) { if (data) data.stop(); $this.data('countto', data = new countto(this, options)); } data[method].call(data); }); }; }(jquery));