Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Fairly low-effort JS to set a textarea to grow in height to accomodate the text within.
// This is seven lines of vanilla JS that does most of what larger packages (like do.
// Might not work for your purposes, but it did for mine, and I figured I'd share.
const autogrow = (event) => {
const { target: textarea } = event;
const { textLength, style: { lineHeight, paddingTop, paddingBottom } } = textarea;
const widthInCharacters = parseInt(, 10);
const adjustmentFactor = 0.8; // tune this up or down if the height is too aggressive (or not aggressive enough)
const lines = Math.floor(textLength * adjustmentFactor / widthInCharacters) + 1;
const height = `calc(${lines * lineHeight}em + ${paddingTop} + ${paddingBottom})`; = height;
// React, but you could use plain old HTML if you like.
<textarea placeholder="Suggestions?" name="suggestions" style={{ fontSize: 'inherit', fontFamily: 'inherit', lineHeight: '1.4', margin: '1rem', minHeight: '3em', padding: '8px 10px', width: '50ch' }} required onKeyDown={autogrow} />
// What's going on here:
// Set the textarea to have a width based on character width (50ch in the example above). `ch` is imprecise unless you're using monospace fonts, but it's close enough for most usecases to work.
// The autogrow() function determines the values of the line height, top padding, and bottom padding.
// It figures out (roughly) how many lines are making up the body of text. It then sets the height of the textarea to reflect the contents.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment