1

I want to create a textarea that expands or contracts to fit the content as the browser window is resized. So when the browser window width increases, the height of the textarea should decrease so that it is as tall as the content; when the browswer window width decreases, the height of the textarea should increase to show all of the content. Here's what I have now, with reference to textareas that expand with content input:

var tx = document.getElementsByTagName("textarea");
for (let i = 0; i < tx.length; i++) {
  tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;");
  window.addEventListener("resize", autoResize(tx[i]));
}

function autoResize(el) {
  el.style.height = "auto";
  el.style.height = (this.scrollHeight) + "px";
}

How do I get this to work?
*Edit: clarifying what I mean by auto-resize
*Edit 2: I checked related questions but they all address how textareas resize with user input, whereas I'm asking how they resize when the browser window is resized. I'm new to Javascript so I don't know how to apply these solutions to my problem.

irisnviolets
  • 33
  • 1
  • 4
  • So you want the textarea to expand to 100% of the width and height of the browser window? – Fabian S. Nov 03 '21 at 12:39
  • @fabian-s no. I want to make the textarea as tall as its content – irisnviolets Nov 03 '21 at 13:19
  • 1
    I believe you will find this thread helpful.. [https://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize](https://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize) – NotTheWaquar Nov 03 '21 at 13:28

1 Answers1

0

If you want the textarea to expand depending on browser window, u can use viewport units.

Vh stands for 1% of the viewport height and vw for 1% of the viewport width.

100vh //100% of the viewport height
100vw //100% of the viewport width
  • Thank you. However, what I mean here is to make the textarea as tall as its content. I'm sorry if I didn't make that clear. – irisnviolets Nov 03 '21 at 13:19
  • [Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?](https://stackoverflow.com/questions/2803880/is-there-a-way-to-get-a-textarea-to-stretch-to-fit-its-content-without-using-php) –  Nov 03 '21 at 14:35