-4

I would like to know how I would be able to set a min and max font-size for a fixed width div that accepts variable text. I looked at a similar question but it didn't provide a plain Javascript approach.

If the text is short the font-size would be 12px, if it's multi-line it can get down to a minimum of 8px for example. How would I be able to accomplish this in plain javascript?

Thank you!

Community
  • 1
  • 1
user2163224
  • 131
  • 2
  • 3
  • 12
  • *`"I be able"`* .. you mean *we* ;) Please show what you have tried so far. StackOverflow is not a free coding service - nor you can expect vague answers that involve calculating each character size - something you could've done some research beforehand. – Roko C. Buljan Feb 27 '17 at 19:18
  • get the length of the string and change the class of the div accordingly to match css styles you have for the different font sizes https://www.w3schools.com/jsref/jsref_length_string.asp http://stackoverflow.com/questions/195951/change-an-elements-class-with-javascript – Funk Doc Feb 27 '17 at 19:21

1 Answers1

1

Add an event listener to some changing property and then change the font size accordingly.

document.getElementById("testInput").addEventListener("keyup", function(){
 var inputText = document.getElementById("testInput").value; document.getElementById("test").innerHTML = inputText;
if(inputText.length > 10){
  document.getElementById("test").style.fontSize = "8px"; 
}else if(inputText.length > 5){
  document.getElementById("test").style.fontSize = "10px"; 
}else{
  document.getElementById("test").style.fontSize = "12px"; 
}  
 });
<input id="testInput">
<div id="test"></div>
  • Thanks so much @Pankaj! That was very helpful. @Roko: I am not asking that a solution would be presented on a silver platter here, but was looking for any tips in regards on how to go about accomplishing what my objective was. – user2163224 Feb 27 '17 at 21:53