jquery.timeago.js 7.0 KB

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