I have an html div that is of a fixed size and an additional HTML input box that is used to input text. This text is then displayed in the div.
I want the text to always be centred and always be the largest size possible for the number of characters in the string.
I have come up with a working prototype but it doesn’t work too well. The text is not always correctly sized.
function bindText(readElement, writeElement, extra){
//the text from the input form triggered by onkeyup event
var textStr = document.getElementById(readElement).value;
//the div to write the text to
var element = document.getElementById(writeElement);
//the major part of the function that I have just brute forced to try and work out
if(textStr.length > 0){
//check the length of the string
if(textStr.length > 8 && textStr.length < 12){
//set a the font size accordingly
element.style.fontSize = 150;
}
//same again
if(textStr.length >= 12 && textStr.length < 16){
element.style.fontSize = 120;
}
if(textStr.length >= 16 && textStr.length < 20){
element.style.fontSize = 100;
}
if(textStr.length >= 20 && textStr.length < 25){
element.style.fontSize = 80;
}
if(textStr.length >= 25 && textStr.length < 32){
element.style.fontSize = 55;
}
if(textStr.length >= 32 && textStr.length < 40){
element.style.fontSize = 50;
}
if(textStr.length >= 40 && textStr.length < 50){
element.style.fontSize = 45;
}
if(textStr.length >= 76){
element = textStr.splice(0, 75);
}
}
}
Is there a more elegant solution to get more consistent results.?
Thanks in advance
As I can see in your approximation of dependence between font size and length of the text:

I made interpolation for this in form:

and you can see the results of this with parameters:
Now you can replace all your
ifandelse ifby one formula for font sizehcalculation and couplemin(h, max_font_size)andmax(min_font_size, h)for setting of the font minimal and maximum size.