javascript 16 lines · 7 steps

Auto-resizing a textarea to fit its content

A textarea grows with its text by measuring scrollHeight on every input and setting its own height.

Explained by highlit
1function autoResizeTextarea(textarea, { maxHeight = Infinity } = {}) {
2 const resize = () => {
3 textarea.style.height = 'auto';
4 const contentHeight = textarea.scrollHeight;
5 const nextHeight = Math.min(contentHeight, maxHeight);
6 textarea.style.height = `${nextHeight}px`;
7 textarea.style.overflowY = contentHeight > maxHeight ? 'auto' : 'hidden';
8 };
9 
10 textarea.style.resize = 'none';
11 textarea.style.boxSizing = 'border-box';
12 textarea.addEventListener('input', resize);
13 resize();
14 
15 return () => textarea.removeEventListener('input', resize);
16}
01 / 01
STEP 01

Walkthrough

Space play ←→ step click any line
Three takeaways
  1. 1Resetting height to 'auto' before reading scrollHeight is what lets a textarea shrink as well as grow.
  2. 2Clamping with Math.min and toggling overflowY gives you a scrollbar only once a max height is reached.
  3. 3Returning a teardown function makes the listener easy to remove and prevents leaks.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Auto-resizing a textarea to fit its content — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code