I want to trim a string down to a particular pixel width so that it can properly fit in a container. It will be similar to substring, except that I am trimming based on pixel width as opposed to number of characters. is there a built in function for this?
3 Answers
You can do it via css: text-overflow: clip;
Note: This is not supported in FF < 7. Every other browser including IE6 supports it.
Try this:
function trimByPixel(str, width) {
var spn = $('<span style="visibility:hidden"></span>').text(str).appendTo('body');
var txt = str;
while (spn.width() > width) { txt = txt.slice(0, -1); spn.text(txt + "..."); }
return txt;
}
3 Comments
well actually
I know. that is not what I'm after.
Gordon Gustafson
FF < 7? I just upgraded to 5.0.1, so I don't think there's even a beta for Firefox 6 yet... :D
Mrchief
:) You can get FF8 alpha release if you go to nightly builds: nightly.mozilla.org
CSS might be the easiest/best option, especially if you're trying to keep text confined to an area. Check out both word-wrap and text-overflow, as they might be v
1 Comment
well actually
I already know about those and they are not what I'm looking for.
overflow: hidden.