Last active
August 29, 2015 13:57
-
-
Save m-vdb/9684452 to your computer and use it in GitHub Desktop.
A simple counter for an element containing a number.
This file contains hidden or 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
/* | |
Usage: | |
<span class="counter">10</span> | |
$(".counter").countTo({ | |
step: 5, // step, integer | |
start: 10, | |
stop: 20 | |
length: 500 // total duration in ms | |
}); | |
*/ | |
(function($){ | |
var defaultOptions = { | |
step: 1, | |
length: 1000 | |
}; | |
function init ($el, options) { | |
var opts = {}; | |
$.extend(true, opts, defaultOptions, options); | |
if (opts.start === undefined) { | |
opts.start = parseInt($el.html(), 10) || 0; | |
} | |
if (opts.stop === undefined) { | |
opts.stop = opts.start + opts.step; | |
} | |
if (opts.start > opts.stop && opts.step > 0) { | |
opts.step = -opts.step; | |
} | |
opts.interval = opts.length / Math.abs(opts.start - opts.stop); | |
return opts; | |
} | |
$.fn.countTo = function(options) { | |
var $this = $(this); | |
options = init($this, options); | |
var counter = options.start; | |
var timer = setInterval(function () { | |
if ((counter >= options.stop && options.step >= 0) || | |
(counter <= options.stop && options.step <= 0) | |
) { | |
clearInterval(timer); | |
$this.html(options.stop); | |
return; | |
} | |
counter += options.step; | |
$this.html(counter); | |
}, options.interval); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment