JSFiddle - React, Tailwind, and code Playground

by Santosh Thakur

HTML

<input id="theInput" type="text" class="input-element" value="1">

CSS

body {
   background: #666;
 }

 .input-element {
   border: 0;
   padding: 2px;
   background: #fff;
   font: 12pt sans-serif;
 }

 .tmp-element {
   visibility: hidden;
   white-space: pre;
 }

JavaScript

var inputEl = document.getElementById("theInput");

function getWidthOfInput() {
  var tmp = document.createElement("span");
  tmp.className = "input-element tmp-element";
  tmp.innerHTML = inputEl.value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  document.body.appendChild(tmp);
  var theWidth = tmp.getBoundingClientRect().width;
  document.body.removeChild(tmp);
  return theWidth;
}

function adjustWidthOfInput() {
  inputEl.style.width = getWidthOfInput() + "px";
}

adjustWidthOfInput();
inputEl.onkeyup = adjustWidthOfInput;