CSS overflow detection in JavaScript
- by ring0
In order to display a line of text (like in a forum), and end that line with "..." if the text would overflow the line (not truncating using the CSS overflow property), there are a number of ways. I'm still seeking the best solution. For instance,
Adding in CSS a "..." as a background-image is a possibility, but it would appear all the time, and this is not a good solution.
Some sites just count the characters and if over - say - 100, truncates the string to keep only 100 (or 97) chars and add a "..." at the end. But fonts are usually not proportional, so the result is not pretty. For instance the space - in pixels - taken by
"AAA" and "iii" is clearly different
"AAA" and "iii" via a proportional font have the same width
There is another idea to get the exact size in pixels of the string:
create in Javascript a DIV
insert the text in it (via innerHTML for instance)
measure the width (via .offsetWidth)
which is not implemented yet. However, I wonder if there could be any browser compatibility problem?
Did any one tried this solution? Other recommendations would be welcome.