
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Auto Grow a Textarea with JavaScript and CSS
Using JavaScript, we can set our TextArea element to automatically grow with its content. The following examples illustrate how we can achieve the above scenario. Let us say the following is our TextArea before adding content −

The following is the TextArea after adding content −

The following is the same TextArea that auto grows itself after adding more content −

Auto Grow a Textarea
Example
Let us see how to auto grow a textarea −
<!DOCTYPE html> <html> <head> <style> * { margin: 3%; color: navy; font-size: 1.2em; } #ta { padding: 2%; resize: none; width: 330px; min-height: 80px; overflow: hidden; box-sizing: border-box; } </style> </head> <body> <form> <label for="ta">Cool TextArea</label> <textarea id="ta"></textarea> </form> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> $("#ta").on('input', function() { var scroll_height = $("#ta").get(0).scrollHeight; $("#ta").css('height', scroll_height + 'px'); }); </script> </body> </html>
Auto Grow a TextArea With a Scrolling Mechanism
Example
We have set scrolling here using the overflow-y property with the value scroll −
<!DOCTYPE html> <html> <head> <style> div { margin: 3%; overflow-y: scroll; } #ta { padding: 2%; resize: none; width: 333px; min-height: 90px; overflow: hidden; box-sizing: border-box; font-size: 1.5em; } </style> </head> <body> <div> <textarea id="ta"></textarea> </div> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> $("#ta").on('input', function() { var scroll_height = $("#ta").get(0).scrollHeight; $("#ta").css('height', scroll_height + 'px'); }); </script> </body> </html>
Advertisements