"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Auto-Size a Textarea with Pure JavaScript?

How to Auto-Size a Textarea with Pure JavaScript?

Published on 2024-11-17
Browse:205

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:

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

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:

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

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.

Release Statement This article is reprinted at: 1729657998 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3