Automatically expand text area
P粉245489391
P粉245489391 2023-10-21 08:49:23
0
2
662

I'm trying to make a simple auto-expanding text area. This is my code:

textarea.onkeyup = function () {
  textarea.style.height = textarea.clientHeight + 'px';
}

But the text area will grow infinitely as you type...

I know there are Dojo and jQuery plugins for this, but I don't want to use them. I looked at their implementation and originally used scrollHeight but did the same thing.

You can start answering and use the text area to play your answer.

P粉245489391
P粉245489391

reply all(2)
P粉786800174

I want the auto-expand area to be limited by the number of rows (e.g. 5 rows). I considered using "em" units, for Rob's solution, however, this is error-prone and doesn't take into account stuff like padding.

This is my idea:

var textarea = document.getElementById("textarea");
var limitRows = 5;
var messageLastScrollHeight = textarea.scrollHeight;

textarea.oninput = function() {
    var rows = parseInt(textarea.getAttribute("rows"));
    // If we don't decrease the amount of rows, the scrollHeight would show the scrollHeight for all the rows
    // even if there is no text.
    textarea.setAttribute("rows", "1");

    if (rows < limitRows && textarea.scrollHeight > messageLastScrollHeight) {
        rows++;
    } else if (rows > 1 && textarea.scrollHeight < messageLastScrollHeight) {
        rows--;
    }

    messageLastScrollHeight = textarea.scrollHeight;
    textarea.setAttribute("rows", rows);
};

Fiddle:http://jsfiddle.net/cgSj3/

P粉447785031

Reset the height before correctly expanding/shrinking the text area using scrollHeight. Math.min() Can be used to set the height limit of the text area.

Code:

var textarea = document.getElementById("textarea");
var heightLimit = 200; /* Maximum height: 200px */

textarea.oninput = function() {
  textarea.style.height = ""; /* Reset the height*/
  textarea.style.height = Math.min(textarea.scrollHeight, heightLimit) + "px";
};

Fiddle: http://jsfiddle.net/gjqWy/155

Note: input events are not supported in IE8 and earlier. If you also want to support this ancient browser, please use keydown or keyup and onpaste and/or oncut.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template