Home > Web Front-end > JS Tutorial > body text

How to Auto-Size a Textarea with Pure JavaScript?

Linda Hamilton
Release: 2024-10-23 13:25:30
Original
695 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!