jquery-countTo.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. Plugin Name: Count To
  3. Written by: Matt Huggins - https://github.com/mhuggins/jquery-countTo
  4. */
  5. (function ($) {
  6. $.fn.countTo = function (options) {
  7. options = options || {};
  8. return $(this).each(function () {
  9. // set options for current element
  10. var settings = $.extend({}, $.fn.countTo.defaults, {
  11. from: $(this).data('from'),
  12. to: $(this).data('to'),
  13. speed: $(this).data('speed'),
  14. refreshInterval: $(this).data('refresh-interval'),
  15. decimals: $(this).data('decimals')
  16. }, options);
  17. // how many times to update the value, and how much to increment the value on each update
  18. var loops = Math.ceil(settings.speed / settings.refreshInterval),
  19. increment = (settings.to - settings.from) / loops;
  20. // references & variables that will change with each update
  21. var self = this,
  22. $self = $(this),
  23. loopCount = 0,
  24. value = settings.from,
  25. data = $self.data('countTo') || {};
  26. $self.data('countTo', data);
  27. // if an existing interval can be found, clear it first
  28. if (data.interval) {
  29. clearInterval(data.interval);
  30. }
  31. data.interval = setInterval(updateTimer, settings.refreshInterval);
  32. // initialize the element with the starting value
  33. render(value);
  34. function updateTimer() {
  35. value += increment;
  36. loopCount++;
  37. render(value);
  38. if (typeof(settings.onUpdate) == 'function') {
  39. settings.onUpdate.call(self, value);
  40. }
  41. if (loopCount >= loops) {
  42. // remove the interval
  43. $self.removeData('countTo');
  44. clearInterval(data.interval);
  45. value = settings.to;
  46. if (typeof(settings.onComplete) == 'function') {
  47. settings.onComplete.call(self, value);
  48. }
  49. }
  50. }
  51. function render(value) {
  52. var formattedValue = settings.formatter.call(self, value, settings);
  53. $self.text(formattedValue);
  54. }
  55. });
  56. };
  57. $.fn.countTo.defaults = {
  58. from: 0, // the number the element should start at
  59. to: 0, // the number the element should end at
  60. speed: 1000, // how long it should take to count between the target numbers
  61. refreshInterval: 100, // how often the element should be updated
  62. decimals: 0, // the number of decimal places to show
  63. formatter: formatter, // handler for formatting the value before rendering
  64. onUpdate: null, // callback method for every time the element is updated
  65. onComplete: null // callback method for when the element finishes updating
  66. };
  67. function formatter(value, settings) {
  68. return value.toFixed(settings.decimals);
  69. }
  70. }(jQuery));