forked from bfintal/Counter-Up
-
Notifications
You must be signed in to change notification settings - Fork 4
/
jquery.counterup.js
86 lines (70 loc) · 2.61 KB
/
jquery.counterup.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*!
* jquery.counterup.js 1.0
*
* Copyright 2013, Benjamin Intal http://gambit.ph @bfintal
* Released under the GPL v2 License
*
* Date: Nov 26, 2013
*/
(function( $ ){
"use strict";
$.fn.counterUp = function( options ) {
// Defaults
var settings = $.extend({
'time': 400,
'delay': 10
}, options);
return this.each(function(){
// Store the object
var $this = $(this);
var $settings = settings;
var counterUpper = function() {
var nums = [];
var divisions = $settings.time / $settings.delay;
var num = $this.text();
var isComma = /[0-9]+,[0-9]+/.test(num);
num = num.replace(/,/g, '');
var isInt = /^[0-9]+$/.test(num);
var isFloat = /^[0-9]+\.[0-9]+$/.test(num);
var decimalPlaces = isFloat ? (num.split('.')[1] || []).length : 0;
// Generate list of incremental numbers to display
for (var i = divisions; i >= 1; i--) {
// Preserve as int if input was int
var newNum = parseInt(num / divisions * i);
// Preserve float if input was float
if (isFloat) {
newNum = parseFloat(num / divisions * i).toFixed(decimalPlaces);
}
// Preserve commas if input had commas
if (isComma) {
while (/(\d+)(\d{3})/.test(newNum.toString())) {
newNum = newNum.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
}
nums.unshift(newNum);
}
$this.data('counterup-nums', nums);
$this.text('0');
// Updates the number until we're done
var f = function() {
$this.text($this.data('counterup-nums').shift());
if ($this.data('counterup-nums').length) {
setTimeout($this.data('counterup-func'), $settings.delay);
} else {
delete $this.data('counterup-nums');
$this.data('counterup-nums', null);
$this.data('counterup-func', null);
}
};
$this.data('counterup-func', f);
// Start the count up
setTimeout($this.data('counterup-func'), $settings.delay);
};
// Perform counts when the element gets into view
$this.waypoint(function(direction){
counterUpper();
this.destroy(); //-- Waypoint 3.0 version of triggerOnce
}, { offset: '100%'});
});
};
})( jQuery );