0

I need to calculate textarea height for the text that will be inserted into it. Textarea has fixed width. For example, for textarea with width 271 px and the following text (no linebreaks):

Some complementary text Some complementary text Some complementary text Some complementary text Some complementary text Some complementary text Some complementary text Some complementary text

Textarea height will be 176px.

pic

So the question is: how this 176px can be calculated?

Thank you.

Masha
  • 827
  • 1
  • 10
  • 30

2 Answers2

0

you can use clientHeight property of textarea

DEMO

function calcHeight() {
  let textarea = document.querySelector("textarea");
  console.log(textarea.clientHeight);
}
<textarea row="2" col="100"></textarea>
<button type="button" onclick="calcHeight()">Calculate Height</button>

Try resizing the textarea and click on the button.

enter image description here

Mohammad Faisal
  • 2,144
  • 15
  • 26
  • get rid of the button and querySelector.. i.e: `oninput="calcHeight(this)"`, then is specific to just clientHeight – Lawrence Cherone Mar 17 '20 at 14:35
  • the problem is that i dont have text inserted into text area. I have them separately, so before inserting text into textarea I need to set its height in order to textarea show all text inside it – Masha Mar 17 '20 at 14:37
0

Building on @MohammadFaisal answer

Pass the element to a function to change the height of the textarea.

function setHeight(e) {
  e.style.height = e.scrollHeight + 'px';
}
<textarea row="2" col="100" oninput="setHeight(this)"></textarea>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106