Crop text to fit the container size
by Taavi Rammar

Let's say you have a div and text that has to fit in there. Cutting the text server-side to fixed length will never get you the exact results since the words may just wrap differently. My solution is to lay the text down and with js, cut off the letters (or words, goBySpaces param true) until the div has expected size. This example is using prototype library so you have to load that before using it.

<div style="width: 200px" id="myTextContainer"><span id="myText">
But I must explain to you how all this mistaken idea of
denouncing pleasure and praising pain was born and I will give you a complete
account of the system, and expound the actual teachings of the great explorer
of the truth, the master-builder of human happiness. No one rejects, dislikes,
or avoids pleasure itself, because it is pleasure, but because those who do
not know how to pursue pleasure rationally encounter consequences that are
extremely painful.</span> <a href="http://en.wikipedia.org/wiki/Lorem_ipsum">read more</a></div>


var cropText = function(txtElement, container_to_fit, heightLimit, goBySpaces){
var txt = txtElement.innerHTML;
var i=0;
if(container_to_fit.getHeight() > heightLimit){
while (container_to_fit.getHeight() > heightLimit){
if(goBySpaces === true){
txt = txt.substr(0,txt.lastIndexOf(' '))
} else {
txt = txt.substr(0,txt.length - 1)
}
txtElement.update(txt+'...')
i++;if(i>100){break;}
}
}
if(txtElement.getHeight() > 0){
container_to_fit.style.height=heightLimit+'px'
}
}
cropText($('myText'), $('myTextContainer'),100,true)

It has it's downsides - you have to load more text, it takes some time for client machine to do it.. but it's really helpful when you need your text containers be filled consistantly.

Copyright by techTips