How to get the height of the text inside of a textarea
Asked Answered
T

8

36

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.

Tomchay answered 27/7, 2010 at 7:28 Comment(0)
G
17

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.

Glitter answered 27/7, 2010 at 7:32 Comment(12)
aham so I should create a <span> inside the <textarea>, right?Tomchay
No. The span does not need to be appended to the document at all. It will be disposed of after the above code. I should also note that the code gives the height of the text WITH top/bot padding, as always with a span/div/whatever. If you don't want this padding, CSS can be used.Glitter
Aham :D I think I've got it. Let me try it.Tomchay
I don't know :|, It wasn't me.Tomchay
I should also note that your question was ambiguous, so i renamed it to the current title. It's probably not what you want. Do you want to get the height of "hello world" inside of the textarea? or what?Glitter
I want to get the height of the text what I write in the textarea, your answer is a tricky way to do this, but in my script I have some other things too, currently I'm working on it.Tomchay
I think, if you tell us what you want to make with this height, it would be more clear to us. I put +1 to ItsWarty since it's a common solution he proposed.Gadolinite
CIRK, i have replied to your other question about an auto-resizable textarea with a mockup code. It's not perfect, but hopefully it'll help you, or any other developer wishing to give it a shot.Glitter
A Range is not going to help you. Firstly, Range does not apply to the value of text inputs: there's the selectionStart and selectionEnd properties of the textarea to cover that. Secondly, Range is all about nodes and offsets within the DOM and not about any kind of visual representation. Thirdly, Range doesn't exist in IE (until version 9, which does have it).Stav
the span element is not a textarea elementSeedbed
The span needs to be appended to the document before the offsetHeight returns anything for me. I guess you need to add it where it's the same styling as the textarea, but you don't know what css is applied specifically to the textarea, so I don't see how this solution actually works?Representative
This is not what is being asked here.Bicorn
B
29

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

Burrill answered 27/7, 2010 at 8:1 Comment(2)
Just tested this and it solved a problem I was having with scrollHeight giving strange values (every time you entered/removed a character on IE11, the scroll height increased). By setting the height of text area to 1px first, it gave me the height of the text as required.Anthropolatry
this is great but doesnt work when the textarea or some of its parent is set to display:noneInvertebrate
G
17

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.

Glitter answered 27/7, 2010 at 7:32 Comment(12)
aham so I should create a <span> inside the <textarea>, right?Tomchay
No. The span does not need to be appended to the document at all. It will be disposed of after the above code. I should also note that the code gives the height of the text WITH top/bot padding, as always with a span/div/whatever. If you don't want this padding, CSS can be used.Glitter
Aham :D I think I've got it. Let me try it.Tomchay
I don't know :|, It wasn't me.Tomchay
I should also note that your question was ambiguous, so i renamed it to the current title. It's probably not what you want. Do you want to get the height of "hello world" inside of the textarea? or what?Glitter
I want to get the height of the text what I write in the textarea, your answer is a tricky way to do this, but in my script I have some other things too, currently I'm working on it.Tomchay
I think, if you tell us what you want to make with this height, it would be more clear to us. I put +1 to ItsWarty since it's a common solution he proposed.Gadolinite
CIRK, i have replied to your other question about an auto-resizable textarea with a mockup code. It's not perfect, but hopefully it'll help you, or any other developer wishing to give it a shot.Glitter
A Range is not going to help you. Firstly, Range does not apply to the value of text inputs: there's the selectionStart and selectionEnd properties of the textarea to cover that. Secondly, Range is all about nodes and offsets within the DOM and not about any kind of visual representation. Thirdly, Range doesn't exist in IE (until version 9, which does have it).Stav
the span element is not a textarea elementSeedbed
The span needs to be appended to the document before the offsetHeight returns anything for me. I guess you need to add it where it's the same styling as the textarea, but you don't know what css is applied specifically to the textarea, so I don't see how this solution actually works?Representative
This is not what is being asked here.Bicorn
D
10

In jQuery there is no scrollHeight, so it needs a little workaround. the solution would be:

var areaheight=$("textarea#element")[0].scrollHeight;
$("#element").height(areaheight);

or shorter:

$("#element").height($("#element")[0].scrollHeight)
Declinatory answered 13/3, 2014 at 9:30 Comment(3)
I don't understand why StackOverflow allows people to downvote with no comment... I found this question when I ran into the same problem as the OP and figured a jQuery solution, which works, and which I still use today, and decided to post that as an answer in case other people needed the same. It's a clear answer to the problem, with a code example and explanation... I don't get the downvotes?!Declinatory
I don't know if this is the reason, but when I use this code to update the height of my textarea after typing, it just always adds about 15px of height. If I remove a line, it still enlarges the textarea.Salade
It's not meant for dynamic purposes. If you want it to work dynamically reset the height to auto, then read the scrollheight and set to that height.Declinatory
D
5

You can use element.scrollHeight (just like Patrick answered) but it needs some corrections (I'm using jQuery in example):

1) if your textarea has padding, you need to substract it (top & bottom).

2) if element has already set height, you need to set it to zero (just for measure then set it back, else it returns this height + padding)

var h0 = $(element).height();  // backup height
$(this).height(0); 
var h = $(this).get(0).scrollHeight - $(this).css('paddingTop').replace('px','')*1 - $(this).css('paddingBottom').replace('px','')*1; // actual text height
$(this).height(h0); // set back original height (or new height using h)

There is no need of extra span with same css as textarea.

Defilade answered 17/7, 2017 at 14:47 Comment(2)
I have no idea why other answers, all wrong! Are getting selected and voted up. This is the only correct answer that I found and that really works. Thanks!Fortissimo
This should be the accepted answer. If you have 1000 textareas in a page, you don't really want to create so much load on the client creating spans, applying css, all just to get the text height and destroy to span. Alternatively, you could not use textareas and just create a full css text box with p and divs. But, with textareas, this solution works perfectly, it grows and shrinks with input, even if the page loaded with pre-filled text (unlike most other solutions I was able to find).Exploit
B
1

For anyone using React:

const textarea_ref = useRef(null);
const [idealHeight,setIdealHeight] = useState(0);
const [inputValue,setInputValue] = useState("");


useLayoutEffect(() => {                                           // useLayoutEffect TO AVOID FLICKERING
    textarea_ref.current.style.height = '0px';                    // NEEDS TO SET HEIGHT TO ZERO
    const scrollHeight = textarea_ref.current.scrollHeight;       // TO READ THE CORRECT SCROLL HEIGHT WHEN IT SHRINKS
    textarea_ref.current.removeAttribute('style');                // REMOVE INLINE STYLE THAT WAS ADDED WITH 0px
    setIdealHeight(scrollHeight + 2);                             // NEEDS TO ADD 2. I THINK IT'S BECAUSE OF THE BORDER
  },[inputValue]);

return (
  <textarea
    // USE idealHeight STATE TO SET THE HEIGHT
    value={inputValue}
    onChange={onChange}
    ref={textarea_ref}
  />
);

PS: It still flickers sometimes. At least in Chrome.

Bicorn answered 30/6, 2020 at 12:10 Comment(0)
T
0

You can get the text height by getting the textarea scrollbar height

const textarea = document.getElementByTagName("textarea");
const height = textarea.scrollHeight;

console.log({ height });
Trichroism answered 24/11, 2020 at 22:33 Comment(0)
T
-1

http://www.quirksmode.org/dom/range_intro.html sorry that I can't be of more help.

the problem with you example is that inline text does not have a height, it only has a line-height, for it to have a height it needs to be in display block mode, so that all the lines are added to a block of text, even then it all depends on the width of the box and the font-size, font-family etc.

what ItzWarty suggests is getting the text selection and putting it in a div that has the same font and width as the textarea, which has display block and allows you to get its height.

Tucci answered 27/7, 2010 at 7:47 Comment(0)
P
-1

I am not sure whether I interpret your question correctly, but I personally needed to know the exact height of each line of text. The line-height property does not have the right value (for example, in Safari, it will be rounded to the closest value when actually printing text).

This is my workaround. You should have the following code somewhere at the beginning of the document.

// set one row in the textarea and get its height
element.rows = 1;
var height1 = parseFloat(window.getComputedStyle(element)["height"]);
// set two rows in the textarea and get its height
element.rows = 2;
var height2 = parseFloat(window.getComputedStyle(element)["height"]);
// Now, the line height should be the difference
var inputLineHeight = height2-height1;

The variable inputLineHeight should contain the correct value, in pixel.

Plasia answered 29/12, 2015 at 23:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.