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.
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.
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>