I am making an ajax call to the server and then updating some stats. I want a plugin which animates the numbers.
e.g. initial value = 65 value after ajax call = 98
in a span of 2 seconds, the v开发者_C百科alue displayed increases from 65 to 98 and the user is able to see that - like the digital speedometers or tachometers.
My search has not led me to find a plugin for this. Does anybody know of such plugin?
Here's one potential solution using jQuery's animate(), implemented as a function. The "duration" and "easing" arguments are optional.
function animateNumber($input, num, duration, easing)
{
$input
.data("start", parseInt($input.val()))
.animate({"val":parseInt(num)},
{
easing: easing == undefined ? "linear" : easing,
duration: duration == undefined ? 500 : parseInt(duration),
step: function(fin,obj)
{
var $this = jQuery(this);
var start = parseInt($this.data("start"));
$this.val(parseInt((fin-start)*obj.state) + start );
}
});
}
// Usage
animateNumber($("#my_input_box"), 23);
animateNumber($("#my_input_box"), 23, 1500, "swing"); // 1.5 sec, swing easing
It doesnt have a duration, but it's kinda close. I'm not sure how to integrate a duration at the moment, and had to throw this together rather quickly.
(function($) {
$.fn.animateNumber = function(to) {
var $ele = $(this),
num = parseInt($ele.html()),
up = to > num,
num_interval = Math.abs(num - to) / 90;
var loop = function() {
num = Math.floor(up ? num+num_interval: num-num_interval);
if ( (up && num > to) || (!up && num < to) ) {
num = to;
clearInterval(animation)
}
$ele.html(num);
}
var animation = setInterval(loop, 5);
}
})(jQuery)
var $counter = $("#counter");
$counter.animateNumber(800);
<span id="counter">100</span>
Simshaun's code works perfectly, except in the case where the number to animate to is less than the current value; leading to an infinite loop of numeric flooring.
Here's the updated code,
(function($) {
$.fn.animateNumber = function(to) {
var $ele = $(this),
num = parseInt($ele.html()),
up = to > num,
num_interval = Math.abs(num - to) / 90;
var loop = function() {
num = up ? Math.ceil(num+num_interval) : Math.floor(num-num_interval);
if ( (up && num > to) || (!up && num < to) ) {
num = to;
clearInterval(animation)
}
$ele.html(num);
}
var animation = setInterval(loop, 5);
}
})(jQuery)
var $counter = $("#counter");
$counter.animateNumber(800);
<span id="counter">100</span>
Here is a jquery plugin that allows you to animate numbers:
https://github.com/kajic/jquery-animateNumber
I recently wrote a jQuery plugin for doing a "picker style" animation on numbers using CSS3 transforms and transitions. A blog post describing it with working examples is available here. The code is also available on github and can be downloaded here.
精彩评论