Wednesday, May 27, 2009

Calculating the number of characters that can fit a div or td element

Here is the problem...
I have an div or td element that has fixed width. I need to find the number of characters that could possibly fit its width/length. Character width is different for different characters. As an example "l" might require 2px, but "W" might require 6! With that said, simple division calculation might now always work. One solution is to clip the div area using css. This will truncate the text that is outside of specified width. Example:


<span style="white-space: nowrap;text-indent:10px;overflow:hidden;width:32px;">od oifh sdof od fdo fso dfosdffusdoifouiofusdoisoif</span>


Above code will truncate any text that is over 32 px. However it will not work for td elements.


Only possible way to truncate text over a specified px width in td element is to actually calculate the number of visible characters. Following code will help you find the exact pixel length of any text inside a div:


<div id="sourceDiv" style="position:absolute; z-index:-1">lll</div><br>
<input type="button" value="Check Size" onclick="var box = document.getElementById('sourceDiv'); alert(box.clientWidth + ' x ' + box.clientHeight);" />



Next step is to calculate px width of every possible character you expect to be displayed in your div/td/span. You can either calculate this at the very beginning and cache the results for future use, or you can compute it on demand. To compute individual character width, make an js array of all possible characters. loop through this, and in each iteration replace the sourceDiv's innerhtml to the character in array. Read the width and store it in another array. Now you have an array or map of all possible characters. You should be able to write a simple function that will calculate the number of characters that would be required to fill up a fixed width div/td/span from a input string/text!

Labels: ,

0 Comments:

Post a Comment

<< Home