Explain Codes LogoExplain Codes Logo

How to make HTML text input field grow as you type?

html
responsive-design
css
input-field
Nikita BarsukovbyNikita Barsukov·Feb 19, 2025
TLDR

For an input field that grows with each character typed, JavaScript allows you to modify its size attribute dynamically. Here's how:

document.querySelector('input[type="text"]').oninput = function() { this.size = Math.max(this.value.length, 1); // Higher of size or 1 to avoid blank input };

The oninput event helps (like a helping neighbor) to resize the text input size with respect to the current input string. This size is set to the minimum value of 1 to prevent from collapsing when empty. This method ensures an auto-resizing input field without needing any libraries.

Stay stylish with CSS

Consider the possibility of reducing reliance on JavaScript, or eliminate JavaScript for simpler scenarios. This CSS heaven we're about to visit has got some premium suites for you.

contenteditable — Handle with care

A dynamic input field can also be realized with HTML div and contenteditable attribute. This provides a more fluid experience by dynamically resizing the input field as user types. Caution: it's like a double-edged sword due to potential HTML injection.

div[contenteditable="true"] { display: inline-block; min-width: 50px; max-width: 200px; border: 1px solid #ccc; // Everyone needs some boundaries, right? }
<div contenteditable="true"></div>

Soccer with a hidden soccer ball?

Sometimes, a hidden element could measure text width for resizing the input field. Interesting right?

function resizeInput(input) { var tmp = document.createElement("span"); tmp.className = "hidden"; tmp.innerHTML = input.value.replace(/&/g, "&amp;").replace(/</g, "&lt;") .replace(/>/g, "&gt;"); document.body.appendChild(tmp); input.style.width = tmp.offsetWidth + "px"; document.body.removeChild(tmp); // Clean up after yourself. Mom always said. } document.querySelector('input[type="text"]').oninput = function() { resizeInput(this); };

Ensure the hidden measuring element is appropriately formatted, precisely encoded, and does not become visible (display: none;).

Serve the perfect user interaction

To enhance user experience, use the :focus pseudo-class in CSS to provide interactive feedback akin to turning on headlights (only a bit less dramatic).

input[type="text"]:focus { border-color: #4b9efa; // Because everyone loves a bit of a blue hue. }

Horsepower for different horses AKA Browser quirks

Every browser is like a different action hero. Some like to do things their way (browsers, not the heroes). Let's get some consistency with getComputedStyle or currentStyle for IE:

function getInputWidth(input) { if (input.currentStyle) { return input.currentStyle.width; } else if (window.getComputedStyle) { return window.getComputedStyle(input, null).width; } }

Make use of these tools of the trade to maintain a consistent user interface across platforms.

Smooth and suave with delayed reactions

Introduce delays with setTimeout to make resizing a smooth operation when user types, like serving a well-aged wine. Because nobody likes stutters (not in speech, not in typing).

var resizeDelay; document.querySelector('input[type="text"]').onkeydown = function() { clearTimeout(resizeDelay); resizeDelay = setTimeout(function() { resizeInput(this); }.bind(this), 200); };

jQuery with panache

For the fancier folks, jQuery provides a sleek alternative for input field resizing:

$('input[type="text"]').on('input', function() { $(this).css('width', $(this).val().length + 'ch'); // Size does matter. });

This dynamic expansion depends on the character width ('ch'), rescaling the input field according to the approximate width of typed characters.

Learning from big boys — Soundcloud

Soundcloud's tag input is a class act of dynamic resizing. It's like the Jennifer Aniston of input fields, ever elegant and adapting, from typing to window resizing. Explore open-source projects for more inspiration and insights.

Playing with the 'size' attribute

Modify the size attribute directly with JavaScript, like a DJ with turntables. Combine this with CSS media queries for a responsive design:

window.onresize = function() { var inputFields = document.querySelectorAll('input[type="text"]'); inputFields.forEach(function(input) { // New size calculation based on a cat video...just kidding, window width. }); };

Big picture — Form design

While you engineer a brilliant dynamic growing input field, remember it's part of a bigger form design. Don't let your perfect input field stick out like a sore thumb.