A tiny, dependency-free ES module that grows a <textarea> to fit its content
as the user types, up to an optional maximum height, then lets it scroll.
It is a rewrite of shaack/auto-resize-textarea
by Stefan Haack. The core measuring technique — measure a baseline, then grow by
the scrollHeight delta, which keeps it independent of box-sizing — is his.
This version adds:
- a selector-based entry point (ES module)
- idempotent setup (safe to call again on the same element)
- a
ResizeObserverthat re-measures when the textarea becomes visible (hidden tab/modal) and re-flows when its width changes (responsive layout) - per-element configuration via
data-*attributes
import { autoResizeTextareas } from './auto-resize-textarea.js';
autoResizeTextareas(); // all [data-autoresize]
autoResizeTextareas('textarea.comment'); // custom selector
autoResizeTextareas('textarea', document.querySelector('#dialog')); // scoped to a rootMarkup:
<textarea data-autoresize></textarea>
<textarea data-autoresize data-init-height="80" data-max-height="400"></textarea>| Attribute | Default | Description |
|---|---|---|
data-init-height |
measured | Fixed starting height in px |
data-max-height |
600 |
Maximum height in px before it scrolls |
Recommended CSS:
textarea[data-autoresize] {
resize: none;
overflow-y: auto;
box-sizing: border-box;
}Requires ResizeObserver (all modern browsers, ~2019 and newer). Without it the
textarea still grows on input, but does not re-flow on width or visibility changes.
- Original idea and core algorithm: Stefan Haack — shaack/auto-resize-textarea (MIT)
- Rewrite: Marcel Best
MIT — see the file for the full text and dual copyright.