-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.mncountupwithacceleration.js
72 lines (72 loc) · 2.33 KB
/
jquery.mncountupwithacceleration.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* Author: Tim Garrison
* URI: http://mitnosirrag.tumblr.com
* GitHub: https://github.com/mitnosirrag
* License: Apache 2.0 <http://www.apache.org/licenses/LICENSE-2.0>
*
* jQuery extension to count up with acceleration, so it will count to large
* numbers quickly, but will throttle back as it gets toward the final number
*/
$.fn.extend({
mnCountUpWithAcceleration: function(end,options) {
var t = $(this);
var speed = 1, i = 0, to, a = 6;
var start = t.text();
if ( !end )
end = $(this).text();
end = String(end);
start = parseInt(start.replace(/,/g, ""));
end = parseInt(end.replace(/,/g, ""));
var dir = 'up';
if ( start >= end ) {
dir = 'down';
}
var defaults = {
append: '',
highlightOnComplete: true
}
var opts = $.extend(defaults, options);
i = parseInt(start);
/*
* Thanks to Stackoverflow user: mikez302
* http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript
* License: http://creativecommons.org/licenses/by-sa/3.0/
*/
$.numberWithCommas = function(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
function cuwaTest() {
if ( 0 == Math.abs(end - i) ) {
clearTimeout(to);
t.text($.numberWithCommas(end) + opts.append);
if ( opts.highlightOnComplete ) {
t.parent().effect('highlight',{color:'#efb669'},1000);
}
} else {
cuwaCount();
}
}
function cuwaCount() {
t.text($.numberWithCommas(i));
var diff = Math.abs(end - i);
if ( 5 >= diff ) {
a = 1;
speed = 100;
} else if ( 10 >= diff ) {
a = 1;
speed = 20;
}
if ( 'down' == dir ) {
i-=a;
} else {
i+=a;
}
to = setTimeout(cuwaTest,speed);
}
return this.each(function() {
cuwaTest();
});
}
});