Make a textarea auto-expand
Written byPhuoc Nguyen
Created
03 Sep, 2023
Category
Level 1 — Basic
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.
#Markup
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.html
<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:js
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:
js
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 about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
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