Actually, I follow the tutorial from http://blog.paranoidferret.com/?p=15 but with some minor modification to meet my needs.
@param element - DOM Element placeholder of the text
@param text - the text for truncation
@param width - desired width
@return text - the truncated text with ellipsis
function autoEllipseText(element, text, width){
var inSpan = document.createElement('span');
inSpan.innerHTML = text;
inSpan.style.whiteSpace = 'nowrap';
$(document.body).append(inSpan);
if(inSpan.offsetWidth > width)
{
var i = 1;
inSpan.innerHTML = '';
var len = text.length;
do{
inSpan.innerHTML = text.substr(0, i) + '...';
}while(inSpan.offsetWidth < width && ++i < len);
text = inSpan.innerHTML;
}
$(inSpan).remove();
return text;
}
The code snippet from http://blog.paranoidferret.com/?p=15 does not work when the DOM element is not yet existing or written in the DOM itself. So the workaround I did was to temporarily write the DOM element in the document's body, apply ellipsis on the text, remove the DOM element, and finally, return the text.
Hope you find it useful. :)
No comments:
Post a Comment