This repository has been archived by the owner on Jul 28, 2020. It is now read-only.
forked from tbasse/jquery-truncate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjquery.truncate.min.js
10 lines (10 loc) · 1.68 KB
/
jquery.truncate.min.js
1
2
3
4
5
6
7
8
9
10
(function(a){a.fn.extend({truncate:function(b){var c={width:"auto",token:"…",center:false,addclass:false,addtitle:false};
b=a.extend(c,b);return this.each(function(){var e=a(this),i={fontFamily:e.css("fontFamily"),fontSize:e.css("fontSize"),fontStyle:e.css("fontStyle"),fontWeight:e.css("fontWeight"),"font-variant":e.css("font-variant"),"text-indent":e.css("text-indent"),"text-transform":e.css("text-transform"),"letter-spacing":e.css("letter-spacing"),"word-spacing":e.css("word-spacing"),display:"none"},h=e.text(),g="",d=a("<span/>").css(i).html(h).appendTo("body"),j=d.width(),f=a.fn.isNumber(b.width)?b.width:e.width();
if(j>f){d.text("");if(b.center){g=h.slice(0,a.fn.findTruncPoint((parseInt(f/2,10)+1),h,0,h.length,d,b.token,false,0))+b.token+h.slice(-1*a.fn.findTruncPoint((parseInt(f/2,10)+1),h,0,h.length,d,"",true,0));
}else{g=h.slice(0,a.fn.findTruncPoint(f,h,0,h.length,d,b.token,false,0))+b.token;}if(b.addclass){e.addClass(b.addclass);}if(b.addtitle){e.attr("title",h);
}e.html(g);}d.remove();});},isNumber:function(b){return !isNaN(parseFloat(b))&&isFinite(b);},reverseString:function(b){return b.split("").reverse().join("");
},findTruncPoint:function(j,l,b,d,g,c,e,f){var k="",i="",h=0;f++;if(e){k=a.fn.reverseString(a.fn.reverseString(l).slice(0,b));
i=a.fn.reverseString(a.fn.reverseString(l).slice(0,d));}else{k=l.slice(0,b);i=l.slice(0,d);}if(g.html(i+c).width()<g.html(k+c).width()){return d;
}h=parseInt((b+d)/2,10);if(e){k=a.fn.reverseString(a.fn.reverseString(l).slice(0,h));}else{k=l.slice(0,h);}if(g.html(k+c).width()==j){return h;
}if(g.html(k+c).width()>j){return a.fn.findTruncPoint(j,l,b,(h-1),g,c,e,f);}else{return a.fn.findTruncPoint(j,l,(h+1),d,g,c,e,f);
}}});})(jQuery);