Neatly truncating text to fit a physical dimension

G

Geoff Soper

Does anyone know of a way of neatly truncate a line of text at a given
physical point, i.e. a width specified in pixels. By neatly I mean not
by simply using the overflow CSS property but to truncate the text on
a word boundary and maybe add a '...' or 'cont.'

Many thanks,
Geoff
 
F

Fabian

Geoff Soper hu kiteb:
Does anyone know of a way of neatly truncate a line of text at a given
physical point, i.e. a width specified in pixels. By neatly I mean not
by simply using the overflow CSS property but to truncate the text on
a word boundary and maybe add a '...' or 'cont.'

I don't think this is possible. aiui, this would require that javascript
be able to detect the properties of the font, as well as the size it has
been instructed to display it at, and I think knowing both of those is
beyond javascript.
 
L

Lasse Reichstein Nielsen

Fabian said:
I don't think this is possible. aiui, this would require that javascript
be able to detect the properties of the font, as well as the size it has
been instructed to display it at, and I think knowing both of those is
beyond javascript.

Actually ... (entering unpractical mode)

You *could* start out with a long text in a div, set to not break, and
then keep shortening it and looking at its actual width until it is
shorter than the width you want to assign it to.

It won't be pretty, and I don't think I'd recommend it for anything
practical, but ... just for geeky completeness :)

---
<script type="text/javascript">
function cutToFit(elem) { // elem contains only text
var str = elem.firstChild.nodeValue;
var i = str.length;
while(elem.offsetWidth > elem.parentNode.offsetWidth) {
i--;
var newstr = str.substring(0,i)+"...";
elem.firstChild.nodeValue = newstr;
}
}
</script>
<div style="white-space:nowrap;overflow:visible;">
<span id="foo">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim id est laborum.
</span>
</div>
<script type="text/javascript">
cutToFit(document.getElementById("foo"));
</script>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top