jquery.timeago.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. /**
  2. * Timeago is a jQuery plugin that makes it easy to support automatically
  3. * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
  4. *
  5. * @name timeago
  6. * @version 1.4.0
  7. * @requires jQuery v1.2.3+
  8. * @author Ryan McGeary
  9. * @license MIT License - http://www.opensource.org/licenses/mit-license.php
  10. *
  11. * For usage and examples, visit:
  12. * http://timeago.yarp.com/
  13. *
  14. * Copyright (c) 2008-2013, Ryan McGeary (ryan -[at]- mcgeary [*dot*] org)
  15. */
  16. (function (factory) {
  17. if (typeof define === 'function' && define.amd) {
  18. // AMD. Register as an anonymous module.
  19. define(['jquery'], factory);
  20. } else {
  21. // Browser globals
  22. factory(jQuery);
  23. }
  24. }(function ($) {
  25. $.timeago = function(timestamp) {
  26. if (timestamp instanceof Date) {
  27. return inWords(timestamp);
  28. } else if (typeof timestamp === "string") {
  29. return inWords($.timeago.parse(timestamp));
  30. } else if (typeof timestamp === "number") {
  31. return inWords(new Date(timestamp));
  32. } else {
  33. return inWords($.timeago.datetime(timestamp));
  34. }
  35. };
  36. var $t = $.timeago;
  37. $.extend($.timeago, {
  38. settings: {
  39. refreshMillis: 60000,
  40. allowPast: true,
  41. allowFuture: false,
  42. localeTitle: false,
  43. cutoff: 0,
  44. strings: {
  45. prefixAgo: null,
  46. prefixFromNow: null,
  47. suffixAgo: "ago",
  48. suffixFromNow: "from now",
  49. inPast: 'any moment now',
  50. seconds: "less than a minute",
  51. minute: "about a minute",
  52. minutes: "%d minutes",
  53. hour: "about an hour",
  54. hours: "about %d hours",
  55. day: "a day",
  56. days: "%d days",
  57. month: "about a month",
  58. months: "%d months",
  59. year: "about a year",
  60. years: "%d years",
  61. wordSeparator: " ",
  62. numbers: []
  63. }
  64. },
  65. inWords: function(distanceMillis) {
  66. if(!this.settings.allowPast && ! this.settings.allowFuture) {
  67. throw 'timeago allowPast and allowFuture settings can not both be set to false.';
  68. }
  69. var $l = this.settings.strings;
  70. var prefix = $l.prefixAgo;
  71. var suffix = $l.suffixAgo;
  72. if (this.settings.allowFuture) {
  73. if (distanceMillis < 0) {
  74. prefix = $l.prefixFromNow;
  75. suffix = $l.suffixFromNow;
  76. }
  77. }
  78. if(!this.settings.allowPast && distanceMillis >= 0) {
  79. return this.settings.strings.inPast;
  80. }
  81. var seconds = Math.abs(distanceMillis) / 1000;
  82. var minutes = seconds / 60;
  83. var hours = minutes / 60;
  84. var days = hours / 24;
  85. var years = days / 365;
  86. function substitute(stringOrFunction, number) {
  87. var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
  88. var value = ($l.numbers && $l.numbers[number]) || number;
  89. return string.replace(/%d/i, value);
  90. }
  91. var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
  92. seconds < 90 && substitute($l.minute, 1) ||
  93. minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
  94. minutes < 90 && substitute($l.hour, 1) ||
  95. hours < 24 && substitute($l.hours, Math.round(hours)) ||
  96. hours < 42 && substitute($l.day, 1) ||
  97. days < 30 && substitute($l.days, Math.round(days)) ||
  98. days < 45 && substitute($l.month, 1) ||
  99. days < 365 && substitute($l.months, Math.round(days / 30)) ||
  100. years < 1.5 && substitute($l.year, 1) ||
  101. substitute($l.years, Math.round(years));
  102. var separator = $l.wordSeparator || "";
  103. if ($l.wordSeparator === undefined) { separator = " "; }
  104. return $.trim([prefix, words, suffix].join(separator));
  105. },
  106. parse: function(iso8601) {
  107. var s = $.trim(iso8601);
  108. s = s.replace(/\.\d+/,""); // remove milliseconds
  109. s = s.replace(/-/,"/").replace(/-/,"/");
  110. s = s.replace(/T/," ").replace(/Z/," UTC");
  111. s = s.replace(/([\+\-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
  112. s = s.replace(/([\+\-]\d\d)$/," $100"); // +09 -> +0900
  113. return new Date(s);
  114. },
  115. datetime: function(elem) {
  116. var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title");
  117. return $t.parse(iso8601);
  118. },
  119. isTime: function(elem) {
  120. // jQuery's `is()` doesn't play well with HTML5 in IE
  121. return $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
  122. }
  123. });
  124. // functions that can be called via $(el).timeago('action')
  125. // init is default when no action is given
  126. // functions are called with context of a single element
  127. var functions = {
  128. init: function(){
  129. var refresh_el = $.proxy(refresh, this);
  130. refresh_el();
  131. var $s = $t.settings;
  132. if ($s.refreshMillis > 0) {
  133. this._timeagoInterval = setInterval(refresh_el, $s.refreshMillis);
  134. }
  135. },
  136. update: function(time){
  137. var parsedTime = $t.parse(time);
  138. $(this).data('timeago', { datetime: parsedTime });
  139. if($t.settings.localeTitle) $(this).attr("title", parsedTime.toLocaleString());
  140. refresh.apply(this);
  141. },
  142. updateFromDOM: function(){
  143. $(this).data('timeago', { datetime: $t.parse( $t.isTime(this) ? $(this).attr("datetime") : $(this).attr("title") ) });
  144. refresh.apply(this);
  145. },
  146. dispose: function () {
  147. if (this._timeagoInterval) {
  148. window.clearInterval(this._timeagoInterval);
  149. this._timeagoInterval = null;
  150. }
  151. }
  152. };
  153. $.fn.timeago = function(action, options) {
  154. var fn = action ? functions[action] : functions.init;
  155. if(!fn){
  156. throw new Error("Unknown function name '"+ action +"' for timeago");
  157. }
  158. // each over objects here and call the requested function
  159. this.each(function(){
  160. fn.call(this, options);
  161. });
  162. return this;
  163. };
  164. function refresh() {
  165. var data = prepareData(this);
  166. var $s = $t.settings;
  167. if (!isNaN(data.datetime)) {
  168. if ( $s.cutoff == 0 || distance(data.datetime) < $s.cutoff) {
  169. $(this).text(inWords(data.datetime));
  170. }
  171. }
  172. return this;
  173. }
  174. function prepareData(element) {
  175. element = $(element);
  176. if (!element.data("timeago")) {
  177. element.data("timeago", { datetime: $t.datetime(element) });
  178. var text = $.trim(element.text());
  179. if ($t.settings.localeTitle) {
  180. element.attr("title", element.data('timeago').datetime.toLocaleString());
  181. } else if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) {
  182. element.attr("title", text);
  183. }
  184. }
  185. return element.data("timeago");
  186. }
  187. function inWords(date) {
  188. return $t.inWords(distance(date));
  189. }
  190. function distance(date) {
  191. return (new Date().getTime() - date.getTime());
  192. }
  193. // fix for IE6 suckage
  194. document.createElement("abbr");
  195. document.createElement("time");
  196. }));