Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. (function ($) {
  2. $.fn.countTo = function (options) {
  3. options = options || {};
  4.  
  5. return $(this).each(function () {
  6. var settings = $.extend({}, $.fn.countTo.defaults, {
  7. from: $(this).data('from'),
  8. to: $(this).data('to'),
  9. speed: $(this).data('speed'),
  10. refreshInterval: $(this).data('refresh-interval'),
  11. decimals: $(this).data('decimals')
  12. }, options);
  13. var loops = Math.ceil(settings.speed / settings.refreshInterval),
  14. increment = (settings.to - settings.from) / loops;
  15. var self = this,
  16. $self = $(this),
  17. loopCount = 0,
  18. value = settings.from,
  19. data = $self.data('countTo') || {};
  20.  
  21. $self.data('countTo', data);
  22. if (data.interval) {
  23. clearInterval(data.interval);
  24. }
  25. data.interval = setInterval(updateTimer, settings.refreshInterval);
  26. render(value);
  27. function updateTimer() {
  28. value += increment;
  29. loopCount++;
  30.  
  31. render(value);
  32.  
  33. if (typeof(settings.onUpdate) == 'function') {
  34. settings.onUpdate.call(self, value);
  35. }
  36.  
  37. if (loopCount >= loops) {
  38. $self.removeData('countTo');
  39. clearInterval(data.interval);
  40. value = settings.to;
  41.  
  42. if (typeof(settings.onComplete) == 'function') {
  43. settings.onComplete.call(self, value);
  44. }
  45. }
  46. }
  47.  
  48. function render(value) {
  49. var formattedValue = settings.formatter.call(self, value, settings);
  50. $self.html(formattedValue);
  51. }
  52. });
  53. };
  54. $.fn.countTo.defaults = {
  55. from: 0,
  56. to: 0,
  57. speed: 1000,
  58. refreshInterval: 100,
  59. decimals: 0,
  60. formatter: formatter,
  61. onUpdate: null,
  62. onComplete: null
  63. };
  64.  
  65. function formatter(value, settings) {
  66. return value.toFixed(settings.decimals);
  67. }
  68. }(jQuery));
  69. jQuery(function ($) {
  70. $('.count-number').data('countToOptions', {
  71. formatter: function (value, options) {
  72. return value.toFixed(options.decimals).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');
  73. }
  74. });
  75. $('.timer').each(count);
  76. function count(options) {
  77. var $this = $(this);
  78. options = $.extend({}, options || {}, $this.data('countToOptions') || {});
  79. $this.countTo(options);
  80. }
  81. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement