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

How Can I Create Self-Adjusting Textareas in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-15 06:30:11414browse

How Can I Create Self-Adjusting Textareas in JavaScript?

Auto-height Textareas

One common challenge when working with textareas is ensuring they adjust their height to accommodate the user's input without the need for a scrollbar. This concern arises in scenarios where the textarea's content often varies in length. Here's how you can achieve this using pure JavaScript:

The code snippet provided leverages a JavaScript function named auto_grow that dynamically adjusts the textarea's height based on its content:

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

In the CSS, you can define the following styles to remove the scrollbar and set minimum and maximum heights:

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

To implement this functionality, simply add the oninput attribute to your