0

There are plenty of StackOverflow examples of an auto-height Textarea. One example is this:

https://stackoverflow.com/a/24676492/1634905

<textarea oninput="auto_grow(this)"></textarea>

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

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

Is there a similar solution that contains auto-width too? Basically both auto-width and auto-height?

When I try a similar way to retrieve the element.scrollWidth, it continues to give me the original width of the text area.

https://jsfiddle.net/on7zasd3/


EDIT:

I think I figured it out. (Ps, I am not sure why the code formatting is broken after here on StackOverflow?)

  1. I had to specify cols="1" on the text area

  2. I also had to perform the element.style.width = "auto"; and set the texture's width to that before performing the height auto one.

  3. Textarea also requires white-space: nowrap; CSS:

    function auto_grow(element) { element.style.width = "auto"; console.log(element.scrollHeight+", "+element.scrollWidth) element.style.width = (element.scrollWidth)+"px";

     element.style.height = "auto";
     console.log(element.scrollHeight+", "+element.scrollWidth)
     element.style.height = (element.scrollHeight)+"px";
    

    }

    textarea { resize: none; overflow: hidden; min-height: 30px; min-width: 30px; white-space: nowrap; }

Ahmad Habib
  • 2,053
  • 1
  • 13
  • 28

1 Answers1

0

I think I figured it out.

  1. I had to specify cols="1" on the text area

  2. I also had to perform the element.style.width = "auto"; and set the texture's width to that before performing the height auto one.

  3. Textarea also requires white-space: nowrap; CSS

    function auto_grow(element) { element.style.width = "auto"; console.log(element.scrollHeight+", "+element.scrollWidth) element.style.width = (element.scrollWidth)+"px";

     element.style.height = "auto";
     console.log(element.scrollHeight+", "+element.scrollWidth)
     element.style.height = (element.scrollHeight)+"px";
    

    }

    textarea { resize: none; overflow: hidden; min-height: 30px; min-width: 30px; white-space: nowrap; }

https://jsfiddle.net/on7zasd3/3/