JSFiddle - React, Tailwind, and code Playground

by Serhii Matrunchyk

HTML

<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Caveat&display=swap" rel="stylesheet">

<input id="my_input">

<span id="text-width-tester" style="font: 30px 'Caveat', cursive;"></span>

CSS

input {
      font: 30px 'Caveat', cursive; 
      width: 250px;
      height: 25px;
      text-align: center;
}

span {
  visibility: hidden;
    position: absolute;
    background: gray;
    z-index: 100;
    margin-top: -100px;
}

JavaScript

const measurer = document.querySelector('#text-width-tester');
        
// txt is the text to measure, font is the full CSS font declaration,
// e.g. "bold 12px Verdana"
function measureText(txt, font) {  
  measurer.style.font = font;
  measurer.innerText = txt;
  
  return measurer.getBoundingClientRect().width;
}

$(function() {
    $('#my_input').keyup(function() {
        var $input = $('input'),
        txt = $input.val(),
        maxWidth = 255,
        font = "36px 'Caveat', cursive";
    // see how big the text is at the default size
    
    var textWidth = measureText(txt, font);
    
        console.log(textWidth);
    if (textWidth > maxWidth) {
        // if it's too big, calculate a new font size
        // the extra .9 here makes up for some over-measures
        font = (36 * maxWidth / textWidth * .9) + "px 'Caveat', cursive";
        
        // and set the style on the input
        $input.css({font:font});
    } else {
        // in case the font size has been set small and 
        // the text was then deleted
        $input.css({font:font});
    }
        
    })
});