Reputation: 3184
I have some numbered statistics on my page and I'd like to make them a little more visually appealing. I thought it might be cool to use jQuery to simulate counting up to that number.
So on page load, say the number is 32. The number would start at 0 and count up to 32, with some delay interval between each number.
How would I accomplish this? This is the code that I tried, but it's not working. It captures the number(s) on the page (there are 3 statRibbons), but it's not visually counting up where I can see each number 0, 1, 2, 3, etc. Ideally, it would count up each ribbon one at a time instead of at the same time, but if it requires bulky extra code, then that's okay. The .each should take care of this anyway, I would think.
$(function() {
$(".statRibbon .bigStat span").each(function() {
var tmp = this.innerHTML;
var i = 0;
while(i != tmp) {
$(".statRibbon .bigStat span").innerHTML(i++);
alert(i);
}
});
});
Upvotes: 5
Views: 19065
Reputation: 191
If someone wants to increase counter with certain increment then use,
// HTML
<span class="stat-count">10000</span>
// JS
$(function() {
function count($this){
var current = parseInt($this.html(), 10);
current = current + 50; /* Where 50 is increment */
$this.html(++current);
if(current > $this.data('count')){
$this.html($this.data('count'));
} else {
setTimeout(function(){count($this)}, 5);
}
}
$(".stat-count").each(function() {
$(this).data('count', parseInt($(this).html(), 10));
$(this).html('0');
count($(this));
});
});
Jquery count numbers on page load with certain limit, counting time and counting increment.
Upvotes: 4
Reputation: 2303
I'd replace the while with a setInteval
$(function() {
$(".statRibbon .bigStat span").each(function() {
var that = $(this),
tmp = that.html(),
i = 0,
interval;
that.html(0);
interval = setInterval(function() {
that.html(++i);
if (i === +tmp) clearInterval(interval);
}, 50);
});
});
Upvotes: 3
Reputation: 10407
How does this work for you?
Change the 50
at the end of the setTimeout function to change the speed it counts in miliseconds.
Upvotes: 12
Reputation: 1013
It appears to me that you need some kind of sleep or delay in your loop before or after you alert the number. Try the setTimeout
method.
You can find more information in this question here: Jquery: how to sleep or delay?
Upvotes: 1