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
Release: 2024-12-16 03:05:10
Original
750 people have browsed it

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";
}
Copy after login

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

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

Here's an HTML example:

<textarea oninput="auto_grow(this)"></textarea>
Copy after login

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!

source:php.cn
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