countdown-timer.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. ! function ($) {
  2. "use strict";
  3. var instances = [],
  4. defaultOptions = {
  5. precision: 100,
  6. elapse: false,
  7. defer: false
  8. };
  9. /*
  10. * Countdown Timer Class Definition
  11. */
  12. var Countdown = function (el, finalDate, options) {
  13. this.el = el;
  14. this.$el = $(el);
  15. this.interval = null;
  16. this.offset = {};
  17. this.options = $.extend({}, defaultOptions);
  18. this.instanceNumber = instances.length;
  19. instances.push(this);
  20. this.$el.data("countdown-instance", this.instanceNumber);
  21. if (options) {
  22. if (typeof options === "function") {
  23. this.$el.on("update.countdown", options);
  24. this.$el.on("stoped.countdown", options);
  25. this.$el.on("finish.countdown", options);
  26. } else {
  27. this.options = $.extend({}, defaultOptions, options);
  28. }
  29. }
  30. this.setFinalDate(finalDate);
  31. if (this.options.defer === false) {
  32. this.start();
  33. }
  34. };
  35. /*
  36. * Countdown Timer Methods
  37. */
  38. Countdown.prototype.start = function () {
  39. if (this.interval !== null) {
  40. clearInterval(this.interval);
  41. }
  42. var self = this;
  43. this.update();
  44. this.interval = setInterval(function () {
  45. self.update.call(self);
  46. }, this.options.precision);
  47. }
  48. Countdown.prototype.stop = function () {
  49. clearInterval(this.interval);
  50. this.interval = null;
  51. this.dispatchEvent("stoped");
  52. }
  53. Countdown.prototype.toggle = function () {
  54. if (this.interval) {
  55. this.stop();
  56. } else {
  57. this.start();
  58. }
  59. }
  60. Countdown.prototype.pause = function () {
  61. this.stop();
  62. }
  63. Countdown.prototype.resume = function () {
  64. this.start();
  65. }
  66. Countdown.prototype.remove = function () {
  67. this.stop.call(this);
  68. instances[this.instanceNumber] = null;
  69. delete this.$el.data().countdownInstance;
  70. }
  71. Countdown.prototype.setFinalDate = function (value) {
  72. this.finalDate = parseDateString(value);
  73. }
  74. Countdown.prototype.update = function () {
  75. if (this.$el.closest("html").length === 0) {
  76. this.remove();
  77. return;
  78. }
  79. var hasEventsAttached = $._data(this.el, "events") !== undefined,
  80. now = new Date(),
  81. newTotalSecsLeft;
  82. newTotalSecsLeft = this.finalDate.getTime() - now.getTime();
  83. newTotalSecsLeft = Math.ceil(newTotalSecsLeft / 1e3);
  84. newTotalSecsLeft = !this.options.elapse && newTotalSecsLeft < 0 ? 0 : Math.abs(newTotalSecsLeft);
  85. if (this.totalSecsLeft === newTotalSecsLeft || !hasEventsAttached) {
  86. return;
  87. } else {
  88. this.totalSecsLeft = newTotalSecsLeft;
  89. }
  90. this.elapsed = now >= this.finalDate;
  91. this.offset = {
  92. seconds: this.totalSecsLeft % 60,
  93. minutes: Math.floor(this.totalSecsLeft / 60) % 60,
  94. hours: Math.floor(this.totalSecsLeft / 60 / 60) % 24,
  95. days: Math.floor(this.totalSecsLeft / 60 / 60 / 24) % 7,
  96. daysToWeek: Math.floor(this.totalSecsLeft / 60 / 60 / 24) % 7,
  97. daysToMonth: Math.floor(this.totalSecsLeft / 60 / 60 / 24 % 30.4368),
  98. weeks: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 7),
  99. weeksToMonth: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 7) % 4,
  100. months: Math.floor(this.totalSecsLeft / 60 / 60 / 24 / 30.4368),
  101. years: Math.abs(this.finalDate.getFullYear() - now.getFullYear()),
  102. totalDays: Math.floor(this.totalSecsLeft / 60 / 60 / 24),
  103. totalHours: Math.floor(this.totalSecsLeft / 60 / 60),
  104. totalMinutes: Math.floor(this.totalSecsLeft / 60),
  105. totalSeconds: this.totalSecsLeft
  106. };
  107. if (!this.options.elapse && this.totalSecsLeft === 0) {
  108. this.stop();
  109. this.dispatchEvent("finish");
  110. } else {
  111. this.dispatchEvent("update");
  112. }
  113. }
  114. Countdown.prototype.dispatchEvent = function (eventName) {
  115. var event = $.Event(eventName + ".countdown");
  116. event.finalDate = this.finalDate;
  117. event.elapsed = this.elapsed;
  118. event.offset = $.extend({}, this.offset);
  119. event.strftime = strftime(this.offset);
  120. this.$el.trigger(event);
  121. }
  122. /*
  123. * Utility Functions
  124. */
  125. function parseDateString(dateString) {
  126. if (dateString instanceof Date) {
  127. return dateString;
  128. } else {
  129. throw new Error("Couldn't cast `" + dateString + "` to a date object.");
  130. }
  131. }
  132. function escapedRegExp(str) {
  133. var sanitize = str.toString().replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
  134. return new RegExp(sanitize);
  135. }
  136. function strftime(offsetObject) {
  137. var DIRECTIVE_KEY_MAP = {
  138. Y: "years",
  139. m: "months",
  140. n: "daysToMonth",
  141. d: "daysToWeek",
  142. w: "weeks",
  143. W: "weeksToMonth",
  144. H: "hours",
  145. M: "minutes",
  146. S: "seconds",
  147. D: "totalDays",
  148. I: "totalHours",
  149. N: "totalMinutes",
  150. T: "totalSeconds"
  151. };
  152. return function (format) {
  153. var directives = format.match(/%(-|!)?[A-Z]{1}(:[^;]+;)?/gi);
  154. if (directives) {
  155. for (var i = 0, len = directives.length; i < len; ++i) {
  156. var directive = directives[i].match(/%(-|!)?([a-zA-Z]{1})(:[^;]+;)?/),
  157. regexp = escapedRegExp(directive[0]),
  158. modifier = directive[1] || "",
  159. plural = directive[3] || "",
  160. value = null;
  161. directive = directive[2];
  162. if (DIRECTIVE_KEY_MAP.hasOwnProperty(directive)) {
  163. value = DIRECTIVE_KEY_MAP[directive];
  164. value = Number(offsetObject[value]);
  165. }
  166. if (value !== null) {
  167. if (modifier === "!") {
  168. value = pluralize(plural, value);
  169. }
  170. if (modifier === "") {
  171. if (value < 10) {
  172. value = "0" + value.toString();
  173. }
  174. }
  175. format = format.replace(regexp, value.toString());
  176. }
  177. }
  178. }
  179. format = format.replace(/%%/, "%");
  180. return format;
  181. };
  182. }
  183. function pluralize(format, count) {
  184. var plural = "s",
  185. singular = "";
  186. if (format) {
  187. format = format.replace(/(:|;|\s)/gi, "").split(/\,/);
  188. if (format.length === 1) {
  189. plural = format[0];
  190. } else {
  191. singular = format[0];
  192. plural = format[1];
  193. }
  194. }
  195. if (Math.abs(count) > 1) {
  196. return plural;
  197. } else {
  198. return singular;
  199. }
  200. }
  201. /*
  202. * Countdown Timer Plugin Definition
  203. */
  204. $.fn.countdown = function () {
  205. var argumentsArray = Array.prototype.slice.call(arguments, 0);
  206. return this.each(function () {
  207. var instanceNumber = $(this).data("countdown-instance");
  208. if (instanceNumber !== undefined) {
  209. var instance = instances[instanceNumber],
  210. method = argumentsArray[0];
  211. if (Countdown.prototype.hasOwnProperty(method)) {
  212. instance[method].apply(instance, argumentsArray.slice(1));
  213. } else if (String(method).match(/^[$A-Z_][0-9A-Z_$]*$/i) === null) {
  214. instance.setFinalDate.call(instance, method);
  215. instance.start();
  216. } else {
  217. $.error("Method %s does not exist on jQuery.countdown".replace(/\%s/gi, method));
  218. }
  219. } else {
  220. new Countdown(this, argumentsArray[0], argumentsArray[1]);
  221. }
  222. });
  223. };
  224. }(window.jQuery);