Home > Web Front-end > JS Tutorial > How to Create a Self-Resizing TextArea That Shrinks on Content Deletion?

How to Create a Self-Resizing TextArea That Shrinks on Content Deletion?

Susan Sarandon
Release: 2024-12-30 02:08:08
Original
250 people have browsed it

How to Create a Self-Resizing TextArea That Shrinks on Content Deletion?

Creating a TextArea with Auto-Resize that Shrinks

Challenge: Previous attempts to create a textarea with auto-resize failed to shrink the textarea upon content deletion.

Solution:

The provided code from the original thread adjusts the height of the textarea based on its content. However, it does not account for content deletion, resulting in an incorrect clientHeight value.

To overcome this limitation, a more comprehensive solution is needed:

function FitToContentWithShrink(id, maxHeight) {
  var text = id && id.style ? id : document.getElementById(id);
  if (!text) return;

  var newHeight = text.scrollHeight;
  var currentHeight = text.clientHeight;

  // Check if the content has changed
  if (newHeight !== currentHeight) {
    if (newHeight > currentHeight) {
      // If the new height is greater than the current height, expand
      text.style.height = newHeight + "px";
    } else if (newHeight < currentHeight) {
      // If the new height is less than the current height, shrink
      text.style.height = newHeight + "px";
    }
  }
}
Copy after login

Benefits:

  • Shrinks content: This solution correctly calculates the new height based on content changes, including deletion.
  • Reliable across browsers: Supports Firefox, Chrome, IE, Edge, IOS Safari, and Android Browser.
  • Works with pre-loaded text: Handles pre-populated textareas.
  • Versatile: Can be applied to all textareas on a website.

Usage:

window.onload = function () {
  document.getElementById("ta").onkeyup = function () {
    FitToContentWithShrink(this, 500);
  };
};
Copy after login

Additional Note:

Applying JavaScript in strict mode will not affect the functionality of this solution.

The above is the detailed content of How to Create a Self-Resizing TextArea That Shrinks on Content Deletion?. 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