/assets/plugins/counter/jquery.counterup.js

https://github.com/honm118/Demo-Html · JavaScript · 83 lines · 50 code · 16 blank · 17 comment · 7 complexity · 319b28bb622c3a7f5d5517e2ce8d8011 MD5 · raw file

  1. /*!
  2. * jquery.counterup.js 1.0
  3. *
  4. * Copyright 2013, Benjamin Intal http://gambit.ph @bfintal
  5. * Released under the GPL v2 License
  6. *
  7. * Date: Nov 26, 2013
  8. */
  9. (function( $ ){
  10. "use strict";
  11. $.fn.counterUp = function( options ) {
  12. // Defaults
  13. var settings = $.extend({
  14. 'time': 400,
  15. 'delay': 10
  16. }, options);
  17. return this.each(function(){
  18. // Store the object
  19. var $this = $(this);
  20. var $settings = settings;
  21. var counterUpper = function() {
  22. var nums = [];
  23. var divisions = $settings.time / $settings.delay;
  24. var num = $this.text();
  25. var isComma = /[0-9]+,[0-9]+/.test(num);
  26. num = num.replace(/,/g, '');
  27. var isInt = /^[0-9]+$/.test(num);
  28. var isFloat = /^[0-9]+\.[0-9]+$/.test(num);
  29. var decimalPlaces = isFloat ? (num.split('.')[1] || []).length : 0;
  30. // Generate list of incremental numbers to display
  31. for (var i = divisions; i >= 1; i--) {
  32. // Preserve as int if input was int
  33. var newNum = parseInt(num / divisions * i);
  34. // Preserve float if input was float
  35. if (isFloat) {
  36. newNum = parseFloat(num / divisions * i).toFixed(decimalPlaces);
  37. }
  38. // Preserve commas if input had commas
  39. if (isComma) {
  40. while (/(\d+)(\d{3})/.test(newNum.toString())) {
  41. newNum = newNum.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
  42. }
  43. }
  44. nums.unshift(newNum);
  45. }
  46. $this.data('counterup-nums', nums);
  47. $this.text('0');
  48. // Updates the number until we're done
  49. var f = function() {
  50. $this.text($this.data('counterup-nums').shift());
  51. if ($this.data('counterup-nums').length) {
  52. setTimeout($this.data('counterup-func'), $settings.delay);
  53. } else {
  54. delete $this.data('counterup-nums');
  55. $this.data('counterup-nums', null);
  56. $this.data('counterup-func', null);
  57. }
  58. };
  59. $this.data('counterup-func', f);
  60. // Start the count up
  61. setTimeout($this.data('counterup-func'), $settings.delay);
  62. };
  63. // Perform counts when the element gets into view
  64. $this.waypoint(counterUpper, { offset: '100%', triggerOnce: true });
  65. });
  66. };
  67. })( jQuery );