← Back toHTML DOM

Make a textarea auto-expand

Written byPhuoc Nguyen
Level 1 — Basic
03 Sep, 2023
If you want to make a textarea on your website expand as the user types, you can use JavaScript DOM to achieve this. In this post, I'll show you how it's done.


Let's assume you have a basic textarea element with an ID of `textarea`. We'll use this ID later to retrieve the textarea element.
<textarea id="textarea"></textarea>

Capturing user input

Now it's time to capture user input. To do this, you'll need to add an event listener for the `input` event on your textarea element. This event is triggered every time the user types something into the textarea. You can easily set this up using the `addEventListener` method. Here's an example:
const textareaEle = document.getElementById('textarea');

textareaEle.addEventListener('input', () => {
// Code to be executed when user types in textarea

Setting the height

If you want your textarea element to grow and shrink as the user types, you'll need to adjust its height accordingly. Here's how to do it:
textarea.style.height = 'auto';
textarea.style.height = `${textarea.scrollHeight}px`;
In your event listener, you'll want to set the `height` property of the element. To do this, first reset the height to `auto` so you can get the actual height of the contents using `scrollHeight`. Then, set the height of the textarea element to the `scrollHeight` value. This will ensure that the textarea element expands to fit its contents.
It's as easy as pie! Just type some text into the textarea element in the demo below, press Enter to create new lines, and watch as the textarea height adjusts dynamically to fit your text. Give it a try!

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn