jQuery counter to count up to a target number

jQuery counter to count up to a target number



I'm trying to find out if anyone knows about an already existing jQuery plugin that will count up to a target number at a specified speed.



For example, take a look at Google's number of MB of free storage on the Gmail homepage, under the heading that reads "Lots of space". It has a starting number in a <span> tag, and slowly counts upward every second.


<span>



I'm looking for something similar, but I'd like to be able to specify:




10 Answers
10



I ended up creating my own plugin. Here it is in case this helps anyone:


(function($)
$.fn.countTo = function(options) );

// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;

return $(this).each(function()
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);

function updateTimer()
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));

if (typeof(options.onUpdate) == 'function')
options.onUpdate.call(_this, value);


if (loopCount >= loops)
clearInterval(interval);
value = options.to;

if (typeof(options.onComplete) == 'function')
options.onComplete.call(_this, value);



);
;

$.fn.countTo.defaults =
from: 0, // the number the element should start at
to: 100, // 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
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
;
)(jQuery);



Here's some sample code of how to use it:


<script type="text/javascript"><!--
jQuery(function($)
$('.timer').countTo(
from: 50,
to: 2500,
speed: 1000,
refreshInterval: 50,
onComplete: function(value)
console.debug(this);

);
);
//--></script>

<span class="timer"></span>



View the demo on JSFiddle: http://jsfiddle.net/YWn9t/





In case anyone has any suggestions for improvements, I moved this code to Github: github.com/mhuggins/jquery-countTo
– Matt Huggins
Apr 30 '12 at 0:16





FYI - this plugin is available with improvements at: github.com/mhuggins/jquery-countTo
– phirschybar
Jun 2 '14 at 19:25





How to start counter on scroll ?
– user6930268
Aug 3 '16 at 11:13





Is there any option so that counter triggers again on scroll??
– sunilkjt
Nov 21 '16 at 10:42





This counter is fantastic, how can we manipulate it to dynamically update/increase the final "to" amount on the fly and resume the calculation on update.
– Peter Bennett
Aug 6 '17 at 17:11



You can use the jQuery animate function


// Enter num from and to
$(countNum: 99).animate(countNum: 1000,
duration: 8000,
easing:'linear',
step: function()
// What todo on every count
console.log(Math.floor(this.countNum));
,
complete: function()
console.log('finished');

);



http://jsbin.com/upazas/958/





It is worth noting that this doesn't seem to work perfectly. I ran your jsbin example in Chrome, and it inconsistently ended at 998 or 999 instead of 1000.
– Matt Huggins
Feb 4 '13 at 16:37





This is because of Math.floor(). If you try to remove the floor() function you will get the correct number witch is 1000 / 8000 = 0,125 on every step. I believe that the "step:" action is executed on every step except the last one - witch is the "complete:" event
– FDisk
Feb 6 '13 at 10:58






Fair enough. I suppose the complete method could be updated to include this line as well to ensure it reaches the last number: $('#counter').text(this.countNum);
– Matt Huggins
Feb 6 '13 at 16:39


complete


$('#counter').text(this.countNum);





May I ask how would I go about making the number have commas, and two decimal places as if it were a price?
– Matt
Dec 30 '13 at 21:55





Replace Math.floor(this.countNum) with this.countNum.toFixed(2)
– FDisk
Jan 13 '14 at 22:15


Math.floor(this.countNum)


this.countNum.toFixed(2)



I've created the tiniest code to do exactly that. It's not only for counting but for any task that needs to run in a given time. (let's say, do something for 5 seconds):


var step = function(t, elapsed)0;
;

var done = function()
console.log('done counting!');
;


// Do-in settings object
var settings =
step : step,
duration : 3,
done : done,
fps : 24 // optional. Default is requestAnimationFrame
;

// initialize "Do-in" instance
var doin = new Doin(settings);



Don't know about plugins but this shouldn't be too hard:


;(function($)
$.fn.counter = function(options)
// Set default values
var defaults =
start: 0,
end: 10,
time: 10,
step: 1000,
callback: function()

var options = $.extend(defaults, options);
// The actual function that does the counting
var counterFunc = function(el, increment, end, step)
var value = parseInt(el.html(), 10) + increment;
if(value >= end)
el.html(Math.round(end));
options.callback();
else
el.html(Math.round(value));
setTimeout(counterFunc, step, el, increment, end, step);


// Set initial value
$(this).html(Math.round(options.start));
// Calculate the increment on each step
var increment = (options.end - options.start) / ((1000 / options.step) * options.time);
// Call the counter function in a closure to avoid conflicts
(function(e, i, o, s)
setTimeout(counterFunc, s, e, i, o, s);
)($(this), increment, options.end, options.step);

)(jQuery);



Usage:


$('#foo').counter(
start: 1000,
end: 4500,
time: 8,
step: 500,
callback: function()
alert("I'm done!");

);



Example:



http://www.ulmanen.fi/stuff/counter.php



I guess the usage is self-explanatory; in this example, the counter will start from 1000 and count up to 4500 in 8 seconds in 500ms intervals, and will call the callback function when the counting is done.



I do not know about any existing plugins, but it seems fairly easy to write one yourself using the JavaScript Timing Events.





Yeah, I don't think I'll have a problem writing one if I have to, but I would rather use an existing one to save time and dealing with bug issues if possible.
– Matt Huggins
Mar 29 '10 at 18:31





You could literally use the one on the page he sent you. It's an infinite loop. Just adjust it accordingly.
– dclowd9901
Mar 29 '10 at 18:33





Indeed :) I would guess the functionality (and code) is too simple to actually turn it into a useful plugin without too much overhead.
– Veger
Mar 29 '10 at 18:37



A different approach. Use Tween.js for the counter. It allows the counter to slow down, speed up, bounce, and a slew of other goodies, as the counter gets to where its going.



http://jsbin.com/ekohep/2/edit#javascript,html,live



Enjoy :)



PS, doesn't use jQuery - but obviously could.



Try jCounter, it has a customRange setting where you can specify the start and end number, it can count up as well including the fallback you want at the end.



Needed a break, so I cobbled the following together. Not sure it would be worth creating a plugin from though.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Counter
</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script type="text/javascript">
//<![CDATA[
function createCounter(elementId,start,end,totalTime,callback)

var jTarget=jQuery("#"+elementId);
var interval=totalTime/(end-start);
var intervalId;
var current=start;
var f=function()
jTarget.text(current);
if(current==end)

clearInterval(intervalId);
if(callback)

callback();


++current;

intervalId=setInterval(f,interval);
f();

jQuery(document).ready(function()
createCounter("counterTarget",0,20,5000,function()
alert("finished")
)
)
//]]>
</script>
</head>
<body>
<div id="counterTarget"></div>
</body>
</html>



Another way to do this without jQuery would be to use Greensock's TweenLite JS library.



Demo http://codepen.io/anon/pen/yNWwEJ


var display = document.getElementById("display");
var number = param:0;
var duration = 1;

function count()
TweenLite.to(number, duration, param:"+=20", roundProps:"param",
onUpdate:update, onComplete:complete, ease:Linear.easeNone);


function update()
display.innerHTML = number.param;


function complete()
//alert("Complete");


count();



You can use jquery animate function for that.


$( countNum: $('.code').html() ).animate( countNum: 4000 ,
duration: 8000,
easing: 'linear',
step: function ()
$('.code').html(Math.floor(this.countNum) );
,
complete: function ()
$('.code').html(this.countNum);
//alert('finished');

);



Here's the original article
http://mishelshaji.co.in/2018/animated-number-counter-using-jquery/





While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
– Stephen Muecke
Aug 28 at 0:28





I have included the code
– Ashin
Aug 28 at 2:51




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



Would you like to answer one of these unanswered questions instead?

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế