How to Dynamically Change Font Size Based on Text Length Using JavaScript?

Sometimes, we want to dynamically change font size based on text length using JavaScript.

In this article, we’ll look at how to dynamically change the size of font size based on text length using JavaScript.

Dynamically Change Font Size Based on Text Length Using JavaScript

To dynamically change the size of font size based on text length using JavaScript, we can resize the text if the height of the containing div is bigger than the div containing the text.

For instance, we write:

<input type="text" >

<div id="outer" class="container" style="width:80%; height:100px; border:2px solid red; font-size:20px;">

  <div class="output" style="word-break: break-all; word-wrap: break-word;">
  </div>

</div>

to add the input to enter the text and the outer and inner divs.

The inner div will contain the text.

Next, we write:

const input = document.querySelector('input');
const output = document.querySelector('.output');
const outputContainer = document.querySelector('.container');

const resizeToFfit = () => {
  let fontSize = window.getComputedStyle(output).fontSize;
  output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';

  if (output.clientHeight >= outputContainer.clientHeight) {
    resizeToFfit();
  }
}

function processInput() {
  output.innerHTML = this.value;
  output.style.fontSize = '100px';
  resizeToFfit();
}

input.addEventListener('input', processInput);

to select the elements with document.querySelector.

Then we add the resizeToFit function that gets the font size of the output element with getComputedStyle.

Next, we set the fontSize to the parsed font size with:

output.style.fontSize = (parseFloat(fontSize) - 1) + 'px';

Then if output.clientHeight is bigger than or equal to outputContainer.clientHeight, we call resizeToFit to resize the text.

Then we add the processInput function that takes the input value with this.value and assign it to output.innerHTML to show the text.

Next, we set the font size of the text to 100px.

And finally, we call resizeToFit to make the text fit in the box.

Then we call input.addEventListener to listen to the input event and run processInput when we type in something into the input.

Conclusion

To dynamically change the size of font size based on text length using JavaScript, we can resize the text if the height of the containing div is bigger than the div containing the text.