dotdotdot.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. /*
  2. * jQuery dotdotdot 1.8.3
  3. *
  4. * Copyright (c) Fred Heusschen
  5. * www.frebsite.nl
  6. *
  7. * Plugin website:
  8. * dotdotdot.frebsite.nl
  9. *
  10. * Licensed under the MIT license.
  11. * http://en.wikipedia.org/wiki/MIT_License
  12. */
  13. (function($, undef) {
  14. 'use strict';
  15. if ($.fn.dotdotdot) {
  16. return;
  17. }
  18. $.fn.dotdotdot = function(o) {
  19. if (this.length === 0) {
  20. $.fn.dotdotdot.debug('No element found for "' + this.selector + '".');
  21. return this;
  22. }
  23. if (this.length > 1) {
  24. return this.each(
  25. function() {
  26. $(this).dotdotdot(o);
  27. }
  28. );
  29. }
  30. var $dot = this;
  31. var orgContent = $dot.contents();
  32. if ($dot.data('dotdotdot')) {
  33. $dot.trigger('destroy.dot');
  34. }
  35. $dot.data('dotdotdot-style', $dot.attr('style') || '');
  36. $dot.css('word-wrap', 'break-word');
  37. if ($dot.css('white-space') === 'nowrap') {
  38. $dot.css('white-space', 'normal');
  39. }
  40. $dot.bind_events = function() {
  41. $dot.bind(
  42. 'update.dot',
  43. function(e, c) {
  44. $dot.removeClass("is-truncated");
  45. e.preventDefault();
  46. e.stopPropagation();
  47. switch (typeof opts.height) {
  48. case 'number':
  49. opts.maxHeight = opts.height;
  50. break;
  51. case 'function':
  52. opts.maxHeight = opts.height.call($dot[0]);
  53. break;
  54. default:
  55. opts.maxHeight = getTrueInnerHeight($dot);
  56. break;
  57. }
  58. opts.maxHeight += opts.tolerance;
  59. if (typeof c != 'undefined') {
  60. if (typeof c == 'string' || ('nodeType' in c && c.nodeType === 1)) {
  61. c = $('<div />').append(c).contents();
  62. }
  63. if (c instanceof $) {
  64. orgContent = c;
  65. }
  66. }
  67. $inr = $dot.wrapInner('<div class="dotdotdot" />').children();
  68. $inr.contents()
  69. .detach()
  70. .end()
  71. .append(orgContent.clone(true))
  72. .find('br')
  73. .replaceWith(' <br /> ')
  74. .end()
  75. .css({
  76. 'height': 'auto',
  77. 'width': 'auto',
  78. 'border': 'none',
  79. 'padding': 0,
  80. 'margin': 0
  81. });
  82. var after = false,
  83. trunc = false;
  84. if (conf.afterElement) {
  85. after = conf.afterElement.clone(true);
  86. after.show();
  87. conf.afterElement.detach();
  88. }
  89. if (test($inr, opts)) {
  90. if (opts.wrap == 'children') {
  91. trunc = children($inr, opts, after);
  92. } else {
  93. trunc = ellipsis($inr, $dot, $inr, opts, after);
  94. }
  95. }
  96. $inr.replaceWith($inr.contents());
  97. $inr = null;
  98. if ($.isFunction(opts.callback)) {
  99. opts.callback.call($dot[0], trunc, orgContent);
  100. }
  101. conf.isTruncated = trunc;
  102. return trunc;
  103. }
  104. ).bind(
  105. 'isTruncated.dot',
  106. function(e, fn) {
  107. e.preventDefault();
  108. e.stopPropagation();
  109. if (typeof fn == 'function') {
  110. fn.call($dot[0], conf.isTruncated);
  111. }
  112. return conf.isTruncated;
  113. }
  114. ).bind(
  115. 'originalContent.dot',
  116. function(e, fn) {
  117. e.preventDefault();
  118. e.stopPropagation();
  119. if (typeof fn == 'function') {
  120. fn.call($dot[0], orgContent);
  121. }
  122. return orgContent;
  123. }
  124. ).bind(
  125. 'destroy.dot',
  126. function(e) {
  127. e.preventDefault();
  128. e.stopPropagation();
  129. $dot.unwatch()
  130. .unbind_events()
  131. .contents()
  132. .detach()
  133. .end()
  134. .append(orgContent)
  135. .attr('style', $dot.data('dotdotdot-style') || '')
  136. .removeClass('is-truncated')
  137. .data('dotdotdot', false);
  138. }
  139. );
  140. return $dot;
  141. }; // /bind_events
  142. $dot.unbind_events = function() {
  143. $dot.unbind('.dot');
  144. return $dot;
  145. }; // /unbind_events
  146. $dot.watch = function() {
  147. $dot.unwatch();
  148. if (opts.watch == 'window') {
  149. var $window = $(window),
  150. _wWidth = $window.width(),
  151. _wHeight = $window.height();
  152. $window.bind(
  153. 'resize.dot' + conf.dotId,
  154. function() {
  155. if (_wWidth != $window.width() || _wHeight != $window.height() || !opts.windowResizeFix) {
  156. _wWidth = $window.width();
  157. _wHeight = $window.height();
  158. if (watchInt) {
  159. clearInterval(watchInt);
  160. }
  161. watchInt = setTimeout(
  162. function() {
  163. $dot.trigger('update.dot');
  164. }, 100
  165. );
  166. }
  167. }
  168. );
  169. } else {
  170. watchOrg = getSizes($dot);
  171. watchInt = setInterval(
  172. function() {
  173. if ($dot.is(':visible')) {
  174. var watchNew = getSizes($dot);
  175. if (watchOrg.width != watchNew.width ||
  176. watchOrg.height != watchNew.height) {
  177. $dot.trigger('update.dot');
  178. watchOrg = watchNew;
  179. }
  180. }
  181. }, 500
  182. );
  183. }
  184. return $dot;
  185. };
  186. $dot.unwatch = function() {
  187. $(window).unbind('resize.dot' + conf.dotId);
  188. if (watchInt) {
  189. clearInterval(watchInt);
  190. }
  191. return $dot;
  192. };
  193. var opts = $.extend(true, {}, $.fn.dotdotdot.defaults, o),
  194. conf = {},
  195. watchOrg = {},
  196. watchInt = null,
  197. $inr = null;
  198. if (!(opts.lastCharacter.remove instanceof Array)) {
  199. opts.lastCharacter.remove = $.fn.dotdotdot.defaultArrays.lastCharacter.remove;
  200. }
  201. if (!(opts.lastCharacter.noEllipsis instanceof Array)) {
  202. opts.lastCharacter.noEllipsis = $.fn.dotdotdot.defaultArrays.lastCharacter.noEllipsis;
  203. }
  204. conf.afterElement = getElement(opts.after, $dot);
  205. conf.isTruncated = false;
  206. conf.dotId = dotId++;
  207. $dot.data('dotdotdot', true)
  208. .bind_events()
  209. .trigger('update.dot');
  210. if (opts.watch) {
  211. $dot.watch();
  212. }
  213. return $dot;
  214. };
  215. // public
  216. $.fn.dotdotdot.defaults = {
  217. 'ellipsis': '... ',
  218. 'wrap': 'word',
  219. 'fallbackToLetter': true,
  220. 'lastCharacter': {},
  221. 'tolerance': 0,
  222. 'callback': null,
  223. 'after': null,
  224. 'height': null,
  225. 'watch': false,
  226. 'windowResizeFix': true,
  227. 'maxLength': null
  228. };
  229. $.fn.dotdotdot.defaultArrays = {
  230. 'lastCharacter': {
  231. 'remove': [' ', '\u3000', ',', ';', '.', '!', '?'],
  232. 'noEllipsis': []
  233. }
  234. };
  235. $.fn.dotdotdot.debug = function(msg) {};
  236. // private
  237. var dotId = 1;
  238. function children($elem, o, after) {
  239. var $elements = $elem.children(),
  240. isTruncated = false;
  241. $elem.empty();
  242. for (var a = 0, l = $elements.length; a < l; a++) {
  243. var $e = $elements.eq(a);
  244. $elem.append($e);
  245. if (after) {
  246. $elem.append(after);
  247. }
  248. if (test($elem, o)) {
  249. $e.remove();
  250. isTruncated = true;
  251. break;
  252. } else {
  253. if (after) {
  254. after.detach();
  255. }
  256. }
  257. }
  258. return isTruncated;
  259. }
  260. function ellipsis($elem, $d, $i, o, after) {
  261. var isTruncated = false;
  262. // Don't put the ellipsis directly inside these elements
  263. var notx = 'a, table, thead, tbody, tfoot, tr, col, colgroup, object, embed, param, ol, ul, dl, blockquote, select, optgroup, option, textarea, script, style';
  264. // Don't remove these elements even if they are after the ellipsis
  265. var noty = 'script, .dotdotdot-keep';
  266. $elem
  267. .contents()
  268. .detach()
  269. .each(
  270. function() {
  271. var e = this,
  272. $e = $(e);
  273. if (typeof e == 'undefined') {
  274. return true;
  275. } else if ($e.is(noty)) {
  276. $elem.append($e);
  277. } else if (isTruncated) {
  278. return true;
  279. } else {
  280. $elem.append($e);
  281. if (after && !$e.is(o.after) && !$e.find(o.after).length) {
  282. $elem[$elem.is(notx) ? 'after' : 'append'](after);
  283. }
  284. if (test($i, o)) {
  285. if (e.nodeType == 3) // node is TEXT
  286. {
  287. isTruncated = ellipsisElement($e, $d, $i, o, after);
  288. } else {
  289. isTruncated = ellipsis($e, $d, $i, o, after);
  290. }
  291. }
  292. if (!isTruncated) {
  293. if (after) {
  294. after.detach();
  295. }
  296. }
  297. }
  298. }
  299. );
  300. $d.addClass("is-truncated");
  301. return isTruncated;
  302. }
  303. function ellipsisElement($e, $d, $i, o, after) {
  304. var e = $e[0];
  305. if (!e) {
  306. return false;
  307. }
  308. var txt = getTextContent(e),
  309. space = (txt.indexOf(' ') !== -1) ? ' ' : '\u3000',
  310. separator = (o.wrap == 'letter') ? '' : space,
  311. textArr = txt.split(separator),
  312. position = -1,
  313. midPos = -1,
  314. startPos = 0,
  315. endPos = textArr.length - 1;
  316. // Only one word
  317. if (o.fallbackToLetter && startPos === 0 && endPos === 0) {
  318. separator = '';
  319. textArr = txt.split(separator);
  320. endPos = textArr.length - 1;
  321. }
  322. if (o.maxLength) {
  323. txt = addEllipsis(txt.trim().substr(0, o.maxLength), o);
  324. setTextContent(e, txt);
  325. } else {
  326. while (startPos <= endPos && !(startPos === 0 && endPos === 0)) {
  327. var m = Math.floor((startPos + endPos) / 2);
  328. if (m == midPos) {
  329. break;
  330. }
  331. midPos = m;
  332. setTextContent(e, textArr.slice(0, midPos + 1).join(separator) + o.ellipsis);
  333. $i.children().each(function() {
  334. $(this).toggle().toggle();
  335. });
  336. if (!test($i, o)) {
  337. position = midPos;
  338. startPos = midPos;
  339. } else {
  340. endPos = midPos;
  341. // Fallback to letter
  342. if (o.fallbackToLetter && startPos === 0 && endPos === 0) {
  343. separator = '';
  344. textArr = textArr[0].split(separator);
  345. position = -1;
  346. midPos = -1;
  347. startPos = 0;
  348. endPos = textArr.length - 1;
  349. }
  350. }
  351. }
  352. if (position != -1 && !(textArr.length === 1 && textArr[0].length === 0)) {
  353. txt = addEllipsis(textArr.slice(0, position + 1).join(separator), o);
  354. setTextContent(e, txt);
  355. } else {
  356. var $w = $e.parent();
  357. $e.detach();
  358. var afterLength = (after && after.closest($w).length) ? after.length : 0;
  359. if ($w.contents().length > afterLength) {
  360. e = findLastTextNode($w.contents().eq(-1 - afterLength), $d);
  361. } else {
  362. e = findLastTextNode($w, $d, true);
  363. if (!afterLength) {
  364. $w.detach();
  365. }
  366. }
  367. if (e) {
  368. txt = addEllipsis(getTextContent(e), o);
  369. setTextContent(e, txt);
  370. if (afterLength && after) {
  371. var $parent = after.parent();
  372. $(e).parent().append(after);
  373. if (!$.trim($parent.html())) {
  374. $parent.remove();
  375. }
  376. }
  377. }
  378. }
  379. }
  380. return true;
  381. }
  382. function test($i, o) {
  383. return ($i.innerHeight() > o.maxHeight || (o.maxLength && $i.text().trim().length > o.maxLength));
  384. }
  385. function addEllipsis(txt, o) {
  386. while ($.inArray(txt.slice(-1), o.lastCharacter.remove) > -1) {
  387. txt = txt.slice(0, -1);
  388. }
  389. if ($.inArray(txt.slice(-1), o.lastCharacter.noEllipsis) < 0) {
  390. txt += o.ellipsis;
  391. }
  392. return txt;
  393. }
  394. function getSizes($d) {
  395. return {
  396. 'width': $d.innerWidth(),
  397. 'height': $d.innerHeight()
  398. };
  399. }
  400. function setTextContent(e, content) {
  401. if (e.innerText) {
  402. e.innerText = content;
  403. } else if (e.nodeValue) {
  404. e.nodeValue = content;
  405. } else if (e.textContent) {
  406. e.textContent = content;
  407. }
  408. }
  409. function getTextContent(e) {
  410. if (e.innerText) {
  411. return e.innerText;
  412. } else if (e.nodeValue) {
  413. return e.nodeValue;
  414. } else if (e.textContent) {
  415. return e.textContent;
  416. } else {
  417. return "";
  418. }
  419. }
  420. function getPrevNode(n) {
  421. do {
  422. n = n.previousSibling;
  423. }
  424. while (n && n.nodeType !== 1 && n.nodeType !== 3);
  425. return n;
  426. }
  427. function findLastTextNode($el, $top, excludeCurrent) {
  428. var e = $el && $el[0],
  429. p;
  430. if (e) {
  431. if (!excludeCurrent) {
  432. if (e.nodeType === 3) {
  433. return e;
  434. }
  435. if ($.trim($el.text())) {
  436. return findLastTextNode($el.contents().last(), $top);
  437. }
  438. }
  439. p = getPrevNode(e);
  440. while (!p) {
  441. $el = $el.parent();
  442. if ($el.is($top) || !$el.length) {
  443. return false;
  444. }
  445. p = getPrevNode($el[0]);
  446. }
  447. if (p) {
  448. return findLastTextNode($(p), $top);
  449. }
  450. }
  451. return false;
  452. }
  453. function getElement(e, $i) {
  454. if (!e) {
  455. return false;
  456. }
  457. if (typeof e === 'string') {
  458. e = $(e, $i);
  459. return (e.length) ?
  460. e :
  461. false;
  462. }
  463. return !e.jquery ?
  464. false :
  465. e;
  466. }
  467. function getTrueInnerHeight($el) {
  468. var h = $el.innerHeight(),
  469. a = ['paddingTop', 'paddingBottom'];
  470. for (var z = 0, l = a.length; z < l; z++) {
  471. var m = parseInt($el.css(a[z]), 10);
  472. if (isNaN(m)) {
  473. m = 0;
  474. }
  475. h -= m;
  476. }
  477. return h;
  478. }
  479. // override jQuery.html
  480. var _orgHtml = $.fn.html;
  481. $.fn.html = function(str) {
  482. if (str != undef && !$.isFunction(str) && this.data('dotdotdot')) {
  483. return this.trigger('update', [str]);
  484. }
  485. return _orgHtml.apply(this, arguments);
  486. };
  487. // override jQuery.text
  488. var _orgText = $.fn.text;
  489. $.fn.text = function(str) {
  490. if (str != undef && !$.isFunction(str) && this.data('dotdotdot')) {
  491. str = $('<div />').text(str).html();
  492. return this.trigger('update', [str]);
  493. }
  494. return _orgText.apply(this, arguments);
  495. };
  496. })(jQuery);
  497. /*
  498. ## Automatic parsing for CSS classes
  499. Contributed by [Ramil Valitov](https://github.com/rvalitov)
  500. ### The idea
  501. You can add one or several CSS classes to HTML elements to automatically invoke "jQuery.dotdotdot functionality" and some extra features. It allows to use jQuery.dotdotdot only by adding appropriate CSS classes without JS programming.
  502. ### Available classes and their description
  503. * dot-ellipsis - automatically invoke jQuery.dotdotdot to this element. This class must be included if you plan to use other classes below.
  504. * dot-resize-update - automatically update if window resize event occurs. It's equivalent to option `watch:'window'`.
  505. * dot-timer-update - automatically update at regular intervals using setInterval. It's equivalent to option `watch:true`.
  506. * dot-load-update - automatically update after the window has beem completely rendered. Can be useful if your content is generated dynamically using using JS and, hence, jQuery.dotdotdot can't correctly detect the height of the element before it's rendered completely.
  507. * dot-height-XXX - available height of content area in pixels, where XXX is a number, e.g. can be `dot-height-35` if you want to set maximum height for 35 pixels. It's equivalent to option `height:'XXX'`.
  508. ### Usage examples
  509. *Adding jQuery.dotdotdot to element*
  510. <div class="dot-ellipsis">
  511. <p>Lorem Ipsum is simply dummy text.</p>
  512. </div>
  513. *Adding jQuery.dotdotdot to element with update on window resize*
  514. <div class="dot-ellipsis dot-resize-update">
  515. <p>Lorem Ipsum is simply dummy text.</p>
  516. </div>
  517. *Adding jQuery.dotdotdot to element with predefined height of 50px*
  518. <div class="dot-ellipsis dot-height-50">
  519. <p>Lorem Ipsum is simply dummy text.</p>
  520. </div>
  521. */
  522. jQuery(document).ready(function($) {
  523. //We only invoke jQuery.dotdotdot on elements that have dot-ellipsis class
  524. $(".dot-ellipsis").each(function() {
  525. //Checking if update on window resize required
  526. var watch_window = $(this).hasClass("dot-resize-update");
  527. //Checking if update on timer required
  528. var watch_timer = $(this).hasClass("dot-timer-update");
  529. //Checking if height set
  530. var height = 0;
  531. var classList = $(this).attr('class').split(/\s+/);
  532. $.each(classList, function(index, item) {
  533. var matchResult = item.match(/^dot-height-(\d+)$/);
  534. if (matchResult !== null)
  535. height = Number(matchResult[1]);
  536. });
  537. //Invoking jQuery.dotdotdot
  538. var x = {};
  539. if (watch_timer)
  540. x.watch = true;
  541. if (watch_window)
  542. x.watch = 'window';
  543. if (height > 0)
  544. x.height = height;
  545. $(this).dotdotdot(x);
  546. });
  547. });
  548. //Updating elements (if any) on window.load event
  549. jQuery(window).on('load', function() {
  550. jQuery(".dot-ellipsis.dot-load-update").trigger("update.dot");
  551. });