shave
Version:
Shave is a javascript plugin that truncates multi-line text within a html element based on set max height
2 lines (1 loc) • 2.09 kB
JavaScript
!function(e){"function"==typeof define&&define.amd?define(e):e()}(function(){"use strict";function q(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),a=[];try{for(;(void 0===t||0<t--)&&!(r=o.next()).done;)a.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return a}function T(e,t,n){if(n||2===arguments.length)for(var r,i=0,o=t.length;i<o;i++)!r&&i in t||((r=r||Array.prototype.slice.call(t,0,i))[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function n(e,t,n){if(void 0===n&&(n={}),void 0===t||isNaN(t))throw Error("maxHeight is required");var r="string"==typeof(e=e)?T([],q(document.querySelectorAll(e)),!1):"length"in e?T([],q(e),!1):[e];if(r.length)for(var e=n.character,i=void 0===e?"…":e,e=n.classname,o=void 0===e?"js-shave":e,e=n.spaces,e=void 0===e||e,a=n.charclassname,l=void 0===a?"js-shave-char":a,a=n.link,c=void 0===a?{}:a,f="boolean"!=typeof e||e,s=c&&"{}"!==JSON.stringify(c)&&c.href,d=s?"a":"span",h=0;h<r.length;h+=1){var u=r[h],v=u.style,y=u.querySelector("."+o),m=void 0===u.textContent?"innerText":"textContent",y=(y&&(u.removeChild(u.querySelector("."+l)),u[m]=u[m]),u[m]),g=f?y.split(" "):y;if(!(g.length<2)){var y=v.height,p=(v.height="auto",v.maxHeight);if(v.maxHeight="none",!(u.offsetHeight<=t)){var x,w=s&&c.textContent?c.textContent:i,j=document.createElement(d),C={className:l,textContent:w};for(x in C)j[x]=C[x],j.textContent=i;if(s)for(var b in c)j[b]=c[b];for(var A=g.length-1,E=0;E<A;){var H,S=g.slice(0,H=E+A+1>>1);u[m]=f?S.join(" "):S,u.insertAdjacentElement("beforeend",j),u.offsetHeight>t?A=H-1:E=H}var w=g.slice(0,A),w=(u[m]=f?w.join(" "):w,u.insertAdjacentElement("beforeend",j),g.slice(A)),w=f?" "+w.join(" "):w,w=document.createTextNode(w),N=document.createElement("span");N.classList.add(o),N.style.display="none",N.appendChild(w),u.insertAdjacentElement("beforeend",N)}v.height=y,v.maxHeight=p}}}var e;"undefined"!=typeof window&&(e=window.$||window.jQuery||window.Zepto)&&(e.fn.shave=function(e,t){return n(this,e,t),this})});