views:

55

answers:

1

Does anyone know what the best method would be to work out how many characters can fit inside a DIV block in HTML using JavaScript?

Any advise would greatly help.

+1  A: 

You could iteratively add your characters to a hidden div and check the width of that. Not sure if there is a better way.

Edit: Something like this:

var targetWidth = document.getElementById('DivToCheck').clientWidth;
var stringToFit = 'abcdefghijk';
var numChars = 0;
for(var i=0; i < stringToFit.length; i++)
{
   document.getElementById('hiddenDiv').innerHTML += stringToFit.charAt(i);
   if (document.getElementById('hiddenDiv').clientWidth > targetWidth)
   {
       numChars = i - 1;
       break;
   }
}

<div id="hiddenDiv" style="visibility: hidden; width: auto;"></div>
nw
bear in mind the following: 1. the hidden div will affect the layout of the page, and so should have *position:absolute;* and, 2. The hidden div will need to match the font stylings of the div to check (e.g. *font-family*, *font-size*, *font-weight*, etc).
Andy E