To adjust width of input field to its input with JavaScript, we set the input’s width as we type.
For instance, we write
<input />
to add the input.
Then we write
const input = document.querySelector("input");
function resizeInput() {
this.style.width = this.value.length + "ch";
}
input.addEventListener("input", resizeInput);
resizeInput.call(input);
to select the input with querySelector
.
We then define the resizeInput
function that sets the width of the input to the width of the number of characters of the input value.
this
is the input element.
Next we call addEventListener
to listen for the input event and call resizeInput
when we type into the input.
And then we call resizeInput.call
with input
to do the initial width adjustment.