Ben Borgers

How to make auto-resizing textarea with JavaScript

December 30, 2020

Here's how to make one of those fancy textareas that gets shorter and taller depending on how much text is in it, using pure javascript.

First, all you need is a plain HTML text box:

<textarea></textarea>

Next, in the javascript, we're going to write a function that makes the textarea the correct height based on how much text is in it. It first makes the text box very short, and then makes it as tall as the content that is not visible.

const textarea = document.querySelector('textarea')

const resize = () => {
  textarea.style.height = '5px'
  textarea.style.height = textarea.scrollHeight + 'px' // e.g. 152 + 'px' = '152px'
}

Now, all we have to do is run this function once the page loads, and run it again every time someone types into the text box:

resize() // run once immediately

textarea.addEventListener('input', resize)

And that's it! The text box will now change height to accommodate how much text you type into it. Here's a CodeSandbox demonstrating the solution.

More blog posts

Subscribe to my newsletter for a monthly round-up of new blog posts and projects Iā€™m working on!

Twitter ↗ RSS feed ↗