Hello and welcome to today’s tutorial. In today’s tutorial, we are going to learn how to create an auto-resize textarea. To create this we need just a few lines of vanilla javascript
So what are textareas? Well, a textarea is similar to a text input but used for a long input text. They have a resize control through which the user can size it to suit his need. But using resize the textarea as you type sounds a bit annoying. A perfect solution here would be a textarea field that auto-adjusts its height depending on the length of text in it. Now that you know what a textarea is and why we need to add an auto-resize function to it, let us start with the coding.
Video Tutorial:
If you would like to code along with me, I have a video tutorial on my youtube channel. You can check it here below:
HTML:
We start with the HTML section. Copy the code provided below and paste it into your HTML section. I have provided the JS code inside the script tag in the HTML document itself. The HTML code consists of just a textarea with a id my-text.
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Auto Resize Textarea</title> <!-- Stylesheet --> <link rel="stylesheet" href="style.css"> </head> <body> <textarea id="my-text" placeholder="Type to autoresize this"></textarea> <script> const myText = document.getElementById("my-text"); myText.style.cssText = `height: ${myText.scrollHeight}px; overflow-y: hidden`; myText.addEventListener("input", function(){ this.style.height = "auto"; this.style.height = `${this.scrollHeight}px`; }); </script> </body> </html>
CSS:
For CSS, I haven’t added any styles to the textarea except for increasing the font size. You can go ahead and add your own styles.
body{ padding: 20px; } textarea{ font-size: 18px; }
Other Tutorials You Might Like:
Javascript:
Coming to javascript, we get the textarea element and assign it a variable myText
. We then set the height of the textarea equal to its scroll height. That means everything that isn’t in the visible part of the textarea (needs to be scrolled to see) is now visible. We need to add this similar thing when a user inputs something. For this, we add an input
event listener to the textarea. So now every time the user inputs something in it, the function immediately sets the height of the textarea to its scrollHeight
.
And that’s it. I hope you liked the tutorial. Drop below your suggestions and feedbacks. You can even download the source code by clicking on the button below.