How to auto-scaling input[type=text] to width of value with JavaScript?

Spread the love

To auto-scaling input[type=text] to width of value with JavaScript, we can put the element in an element and then use that width to set the input’s width.

For instance, we write

<p>
  <span id="hide"></span><input id="txt" type="text" value="type here ..." />
</p>

to add a span and input.

Then we write

#hide {
  position: absolute;
  height: 0;
  overflow: hidden;
  white-space: pre;
}

to hide the span by setting its height to 0.

Then we write

const hide = document.getElementById("hide");
const txt = document.getElementById("txt");

const resize = () => {
  hide.textContent = txt.value;
  txt.style.width = hide.offsetWidth + "px";
};
resize();
txt.addEventListener("input", resize);

to listen to the input’s input evennt with the resize function with addEventListener.

In the resize function, we get the input’s value with txt.value.

We set that as the span’s textContent.

And then we set the span’s width to the input’s width with

txt.style.width = hide.offsetWidth + "px";

Leave a Reply

Your email address will not be published. Required fields are marked *