Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the height of the text inside of a textarea

I have a textarea with the the text Hello World. I would like to get the height of this text.

I've tried to use:

var element = document.getElementById('textarea'); var textHeight = element.innerHTML.offsetHeight; 

and:

var textHeight = element.value.offsetHeight; 

But these don't give the numbers of the text, but the height of the textarea element.

like image 769
Adam Halasz Avatar asked Jul 27 '10 07:07

Adam Halasz


People also ask

Can we use value attribute in textarea?

<textarea> does not support the value attribute.

What is textarea value?

The value property sets or returns the contents of a text area. Note: The value of a text area is the text between the <textarea> and </textarea> tags.


2 Answers

element.scrollHeight is probably worth investigating.

If I was going to approach this (and I've not tested this at all), I'd set the textarea's height to 1px measure the scroll height and then reset the textarea's height.

https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight

like image 131
edeverett Avatar answered Sep 29 '22 23:09

edeverett


Create a span element, set Span's innerHTML to "Hello World".
Get the span's offsetHeight.

var span = document.createElement("span"); span.innerHTML="Hello World"; //or whatever string you want. span.offsetHeight // this is the answer 

note that you must set the span's font style to the textarea's font style.

Your example will NEVER work because innerHTML and value are both strings. String doesn't define offsetWidth.

If you wish to get the height of selected text inside of a textarea, use selectionStart/selectionEnd to find the selected text of the textarea.

like image 39
Warty Avatar answered Sep 29 '22 21:09

Warty