Vanilla Truncation
Holy crap.. someone wrote something without jQuery?!
by rgthree
HTML
<p class="truncate">
This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long. This is going to be too long.
</p>
CSS
p.truncate {
font-size:16px;
line-height:1.5;
height:3em;
border:1px dotted rgba(0,0,0,0.2);
overflow:hidden;
}
JavaScript
(function(){
"use strict";
function truncate(){
var els, i, l, el;
els = document.getElementsByClassName('truncate');
for(i = 0, l = els.length; i < l; i++){
el = els[i];
if(el.getAttribute('data-original-text'))
el.textContent = el.getAttribute('data-original-text');
else
el.setAttribute('data-original-text', el.textContent);
do{
el.textContent = el.textContent.substr(0, el.textContent.length-10);
}while(el.textContent.length && el.scrollHeight > el.offsetHeight);
el.textContent = el.textContent.substr(0, el.textContent.length-3)+'...';
}
}
truncate();
window.addEventListener('resize', truncate);
})();