search

Home  >  Q&A  >  body text

Automatically expand text area

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粉245489391P粉245489391431 days ago694

reply all(2)I'll reply

  • P粉786800174

    P粉7868001742023-10-22 07:17:18

    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>

    reply
    0
  • P粉447785031

    P粉4477850312023-10-22 00:31:05

    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. < /p>

    reply
    0
  • Cancelreply