3

Possible Duplicate:
Calculate text width with Javascript

Alright, so here's what I am looking to see if can be accomplished. I want to take user submitted text (so.. variable length) and place it into a fixed width/height div. If the text will exceed the space allotted, I want to show as much as possible and place an ellipsis (...) at the end, as close to the boundary as I can.

So what I'm wondering... is it possible to tell how much space a certain block of text will take up (javascript)? I'm not looking to use a mono-spaced font, and even if I did I don't know if it would help much.

I'm beginning to wonder if there simply aren't too many variables to account for, and that I'll end up needing to do something less precise, such as outputting a fixed maximum of characters. But I wanted to see if anyone has accomplished something like this before, or if the general consensus was "not possible/not worth the effort." Thanks all!

Community
  • 1
  • 1
dgeare
  • 2,618
  • 5
  • 18
  • 28

2 Answers2

3

Working Fiddle

function width(tex) {
    var text = tex;
    var div = document.createElement("div");
    div.style.position="absolute";
    div.style.top="-999px";
    div.style.left="-999px";
    div.id = "width";
    div.innerHTML=tex;
    document.body.appendChild(div);
    var el = document.getElementById("width");
    var w = el.offsetWidth;
    el.parentNode.removeChild(el);
    return w;
}
var s = parseInt(width("s"), 10);
alert(s);

The above will return width of text!

Community
  • 1
  • 1
Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
  • That was perfect, thank you. Gave me just the direction I needed. By fixing the div's width and using the offsetHeight as a comparison, I can loop through the text, subtracting characters until I get a string which fits into a div of the target size perfectly. Thanks. – dgeare Jan 05 '13 at 21:05
2

A quick search revealed this possible solution for you here.

This may not be exactly what you are looking for. I will keep digging and update this when I find more.

Community
  • 1
  • 1
SnareChops
  • 13,175
  • 9
  • 69
  • 91