Automatically resize textarea height to fit text with JavaScript/jQuery
This post will discuss how to automatically resize textarea height to fit with the text using JavaScript and jQuery.
To automatically resize textarea height to fit the text, we can use the Element.scrollHeight
, which gives the actual height of an element’s content, including overflow. It is the minimum height the element would require to fit all the content on the screen.
The idea is to bind an event handler to the keyup
and keypress
JavaScript event. This is demonstrated below in jQuery:
JS
1 2 3 4 5 6 |
$(document).ready(function() { $('textarea').on('keyup keypress', function() { $(this).height(0); $(this).height(this.scrollHeight); }); }); |
HTML
1 2 3 4 5 |
<label for="story">Tell us your story:</label> <textarea id="story" name="story" rows ="3" cols="33"> It was a dark and stormy night… </textarea> |
Another solution is to use an external library for this task. Autosize is a lightweight, standalone popular JavaScript library to automatically adjust textarea height to fit the text. Here’s a working example:
JS
1 2 3 |
document.addEventListener('DOMContentLoaded', function() { autosize(document.querySelectorAll('#story')); }, false); |
HTML
1 2 3 4 5 6 7 8 9 10 |
<!doctype html> <html lang="en"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/autosize.js/4.0.2/autosize.min.js"></script> </head> <body> <label for="story">Tell us your story:</label> <textarea id="story" name="story" rows ="3" cols="33">It was a dark and stormy night…</textarea> </body> </html> |
Alternatively, you can also use jquery.ns-autogrow or jquery-grab-bag jQuery plugins, which automatically adjust textarea width/height based on user input.
That’s all about automatically resize textarea height to fit text in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)