How to create an auto-resize Textarea in JavaScript
Here, you will learn how to create an auto-resize Textarea in JavaScript that will fit the content. In this article, we will discuss two different ways to automatically resize Textarea as you write content.
Checkout more articles on JavaScript
Method 1: Auto-resize Textarea as user types using JavaScript
In this method, we will use pure JavaScript to auto resize the textarea. For that, we have to use input
addEventListener to resize the Textarea.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!DOCTYPE html> <html lang="en"> <head> <title>Auto-resize Textarea as user types using JavaScript - Clue Mediator</title> </head> <body> <textarea id="myTextarea" style="width: 500px;"></textarea> <script type="text/javascript"> function autoResizeTextarea() { this.style.height = "auto"; this.style.height = `${this.scrollHeight}px`; } var textareaEl = document.querySelector("#myTextarea"); textareaEl.addEventListener('input', autoResizeTextarea, false); </script> </body> </html> |
Method 2: Auto-resize Textarea to fit the content using jQuery
We can do the same example using jQuery. Check out the following jQuery example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!DOCTYPE html> <html lang="en"> <head> <title>Auto resize the textarea to fit the content using jQuery - Clue Mediator</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <textarea id="myTextarea" style="width: 500px;"></textarea> <script type="text/javascript"> $('#myTextarea').on('input', function () { this.style.height = "auto"; this.style.height = `${this.scrollHeight}px`; }); </script> </body> </html> |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂