countUp.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /*
  2. countUp.js
  3. by @inorganik
  4. */
  5. // target = id of html element or var of previously selected html element where counting occurs
  6. // startVal = the value you want to begin at
  7. // endVal = the value you want to arrive at
  8. // decimals = number of decimal places, default 0
  9. // duration = duration of animation in seconds, default 2
  10. // options = optional object of options (see below)
  11. var CountUp = function(target, startVal, endVal, decimals, duration, options) {
  12. var self = this;
  13. self.version = function () { return '1.9.3'; };
  14. // default options
  15. self.options = {
  16. useEasing: true, // toggle easing
  17. useGrouping: true, // 1,000,000 vs 1000000
  18. separator: ',', // character to use as a separator
  19. decimal: '.', // character to use as a decimal
  20. easingFn: easeOutExpo, // optional custom easing function, default is Robert Penner's easeOutExpo
  21. formattingFn: formatNumber, // optional custom formatting function, default is formatNumber above
  22. prefix: '', // optional text before the result
  23. suffix: '', // optional text after the result
  24. numerals: [] // optionally pass an array of custom numerals for 0-9
  25. };
  26. // extend default options with passed options object
  27. if (options && typeof options === 'object') {
  28. for (var key in self.options) {
  29. if (options.hasOwnProperty(key) && options[key] !== null) {
  30. self.options[key] = options[key];
  31. }
  32. }
  33. }
  34. if (self.options.separator === '') {
  35. self.options.useGrouping = false;
  36. }
  37. else {
  38. // ensure the separator is a string (formatNumber assumes this)
  39. self.options.separator = '' + self.options.separator;
  40. }
  41. // make sure requestAnimationFrame and cancelAnimationFrame are defined
  42. // polyfill for browsers without native support
  43. // by Opera engineer Erik Möller
  44. var lastTime = 0;
  45. var vendors = ['webkit', 'moz', 'ms', 'o'];
  46. for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
  47. window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
  48. window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
  49. }
  50. if (!window.requestAnimationFrame) {
  51. window.requestAnimationFrame = function(callback, element) {
  52. var currTime = new Date().getTime();
  53. var timeToCall = Math.max(0, 16 - (currTime - lastTime));
  54. var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall);
  55. lastTime = currTime + timeToCall;
  56. return id;
  57. };
  58. }
  59. if (!window.cancelAnimationFrame) {
  60. window.cancelAnimationFrame = function(id) {
  61. clearTimeout(id);
  62. };
  63. }
  64. function formatNumber(num) {
  65. var neg = (num < 0),
  66. x, x1, x2, x3, i, len;
  67. num = Math.abs(num).toFixed(self.decimals);
  68. num += '';
  69. x = num.split('.');
  70. x1 = x[0];
  71. x2 = x.length > 1 ? self.options.decimal + x[1] : '';
  72. if (self.options.useGrouping) {
  73. x3 = '';
  74. for (i = 0, len = x1.length; i < len; ++i) {
  75. if (i !== 0 && ((i % 3) === 0)) {
  76. x3 = self.options.separator + x3;
  77. }
  78. x3 = x1[len - i - 1] + x3;
  79. }
  80. x1 = x3;
  81. }
  82. // optional numeral substitution
  83. if (self.options.numerals.length) {
  84. x1 = x1.replace(/[0-9]/g, function(w) {
  85. return self.options.numerals[+w];
  86. })
  87. x2 = x2.replace(/[0-9]/g, function(w) {
  88. return self.options.numerals[+w];
  89. })
  90. }
  91. return (neg ? '-' : '') + self.options.prefix + x1 + x2 + self.options.suffix;
  92. }
  93. // Robert Penner's easeOutExpo
  94. function easeOutExpo(t, b, c, d) {
  95. return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
  96. }
  97. function ensureNumber(n) {
  98. return (typeof n === 'number' && !isNaN(n));
  99. }
  100. self.initialize = function() {
  101. if (self.initialized) return true;
  102. self.error = '';
  103. self.d = (typeof target === 'string') ? document.getElementById(target) : target;
  104. if (!self.d) {
  105. self.error = '[CountUp] target is null or undefined'
  106. return false;
  107. }
  108. self.startVal = Number(startVal);
  109. self.endVal = Number(endVal);
  110. // error checks
  111. if (ensureNumber(self.startVal) && ensureNumber(self.endVal)) {
  112. self.decimals = Math.max(0, decimals || 0);
  113. self.dec = Math.pow(10, self.decimals);
  114. self.duration = Number(duration) * 1000 || 2000;
  115. self.countDown = (self.startVal > self.endVal);
  116. self.frameVal = self.startVal;
  117. self.initialized = true;
  118. return true;
  119. }
  120. else {
  121. self.error = '[CountUp] startVal ('+startVal+') or endVal ('+endVal+') is not a number';
  122. return false;
  123. }
  124. };
  125. // Print value to target
  126. self.printValue = function(value) {
  127. var result = self.options.formattingFn(value);
  128. if (self.d.tagName === 'INPUT') {
  129. this.d.value = result;
  130. }
  131. else if (self.d.tagName === 'text' || self.d.tagName === 'tspan') {
  132. this.d.textContent = result;
  133. }
  134. else {
  135. this.d.innerHTML = result;
  136. }
  137. };
  138. self.count = function(timestamp) {
  139. if (!self.startTime) { self.startTime = timestamp; }
  140. self.timestamp = timestamp;
  141. var progress = timestamp - self.startTime;
  142. self.remaining = self.duration - progress;
  143. // to ease or not to ease
  144. if (self.options.useEasing) {
  145. if (self.countDown) {
  146. self.frameVal = self.startVal - self.options.easingFn(progress, 0, self.startVal - self.endVal, self.duration);
  147. } else {
  148. self.frameVal = self.options.easingFn(progress, self.startVal, self.endVal - self.startVal, self.duration);
  149. }
  150. } else {
  151. if (self.countDown) {
  152. self.frameVal = self.startVal - ((self.startVal - self.endVal) * (progress / self.duration));
  153. } else {
  154. self.frameVal = self.startVal + (self.endVal - self.startVal) * (progress / self.duration);
  155. }
  156. }
  157. // don't go past endVal since progress can exceed duration in the last frame
  158. if (self.countDown) {
  159. self.frameVal = (self.frameVal < self.endVal) ? self.endVal : self.frameVal;
  160. } else {
  161. self.frameVal = (self.frameVal > self.endVal) ? self.endVal : self.frameVal;
  162. }
  163. // decimal
  164. self.frameVal = Math.round(self.frameVal*self.dec)/self.dec;
  165. // format and print value
  166. self.printValue(self.frameVal);
  167. // whether to continue
  168. if (progress < self.duration) {
  169. self.rAF = requestAnimationFrame(self.count);
  170. } else {
  171. if (self.callback) self.callback();
  172. }
  173. };
  174. // start your animation
  175. self.start = function(callback) {
  176. if (!self.initialize()) return;
  177. self.callback = callback;
  178. self.rAF = requestAnimationFrame(self.count);
  179. };
  180. // toggles pause/resume animation
  181. self.pauseResume = function() {
  182. if (!self.paused) {
  183. self.paused = true;
  184. cancelAnimationFrame(self.rAF);
  185. } else {
  186. self.paused = false;
  187. delete self.startTime;
  188. self.duration = self.remaining;
  189. self.startVal = self.frameVal;
  190. requestAnimationFrame(self.count);
  191. }
  192. };
  193. // reset to startVal so animation can be run again
  194. self.reset = function() {
  195. self.paused = false;
  196. delete self.startTime;
  197. self.initialized = false;
  198. if (self.initialize()) {
  199. cancelAnimationFrame(self.rAF);
  200. self.printValue(self.startVal);
  201. }
  202. };
  203. // pass a new endVal and start animation
  204. self.update = function (newEndVal) {
  205. if (!self.initialize()) return;
  206. newEndVal = Number(newEndVal);
  207. if (!ensureNumber(newEndVal)) {
  208. self.error = '[CountUp] update() - new endVal is not a number: '+newEndVal;
  209. return;
  210. }
  211. self.error = '';
  212. if (newEndVal === self.frameVal) return;
  213. cancelAnimationFrame(self.rAF);
  214. self.paused = false;
  215. delete self.startTime;
  216. self.startVal = self.frameVal;
  217. self.endVal = newEndVal;
  218. self.countDown = (self.startVal > self.endVal);
  219. self.rAF = requestAnimationFrame(self.count);
  220. };
  221. // format startVal on initialization
  222. if (self.initialize()) self.printValue(self.startVal);
  223. };