Home >Web Front-end >CSS Tutorial >How Can I Create a Self-Adjusting Textarea Height in JavaScript?

How Can I Create a Self-Adjusting Textarea Height in JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-16 03:05:10700browse

How Can I Create a Self-Adjusting Textarea Height in JavaScript?

Textarea Auto Height: Setting Height Based on Content

Q&A:

Q: How can I make the height of a textarea adapt to the height of its text content, eliminating the need for a scrollbar?

A: Here's a JavaScript solution:

function auto_grow(element) {
  element.style.height = "5px";
  element.style.height = (element.scrollHeight) + "px";
}

To use this code, add the following CSS styles to your textarea:

textarea {
  resize: none;
  overflow: hidden;
  min-height: 50px;
  max-height: 100px;
}

Here's an HTML example:

<textarea oninput="auto_grow(this)"></textarea>

This code:

  1. Sets the initial height of the textarea to 5px.
  2. Recalculates the height based on the scroll height, which is the height of the text content.

The above is the detailed content of How Can I Create a Self-Adjusting Textarea Height in 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