Home >Web Front-end >JS Tutorial >How to Auto-Size a Textarea with Pure JavaScript?
Textarea Auto Height
This question aims to eliminate the scrollbar of a textarea and adjust its height to match the content within it. A solution using pure JavaScript code is provided:
<code class="js">function auto_grow(element) { element.style.height = "5px"; element.style.height = (element.scrollHeight) + "px"; }</code>
To ensure the textarea's height resizes dynamically as text is entered, this function is triggered by the oninput event. Additionally, the textarea's CSS properties can be adjusted to disable resizing and overflow, while setting minimum and maximum heights if desired:
<code class="css">textarea { resize: none; overflow: hidden; min-height: 50px; max-height: 100px; }</code>
By implementing these adjustments, the textarea will automatically adjust its height to match the content, eliminating the need for a scrollbar while ensuring a sleek and responsive user experience.
The above is the detailed content of How to Auto-Size a Textarea with Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!