jquery.countTo.js 2.5 KB

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