Home  >  Article  >  Web Front-end  >  How to Auto-Size a Textarea with Pure JavaScript?

How to Auto-Size a Textarea with Pure JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-23 13:25:30696browse

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!

Statement:
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