Reputation: 497
I want to make an animation like this one in Google Analytics on active users.
How would I do this in javascript/jquery?
As requested, what I tried:
<span id="counter">0</span>
$(function ()
{
var $counter = $('#counter'),
startVal = $counter.text(),
currentVal,
endVal = 250;
currentVal = startVal;
var i = setInterval(function ()
{
if (currentVal === endVal)
{
clearInterval(i);
}
else
{
currentVal++;
$counter.text(currentVal);
}
}, 100);
});
But I don't think it's the way to go...
Upvotes: 3
Views: 1788
Reputation: 163478
I would use jQuery's built-in animation for this.
If you pass a function to the step
option for .animate()
, it will be fired for each tick during animation. That way, jQuery will handle all of the easing and what not for you. You just need to handle the data.
$({countValue:0}).animate(
{countValue:346},
{
duration: 5000, /* time for animation in milliseconds */
step: function (value) { /* fired every "frame" */
console.log(value);
}
}
);
In the console, you will see values between 0 and 346, complete with easing.
Upvotes: 8