I expected the .rows
and .cols
property of a textarea element in javascript to tell me the current values, but they don’t, they seem to tell me just the initial markup attribute values, even after the textarea is resized.
function howBigAmI(){
let el= document.getElementById("textarea")
document.getElementById("output").innerHTML=
`${el.rows} rows by ${el.cols} cols, text length=${el.value.length}`
}
howBigAmI()
<p>
How can I read the current textarea rows and cols?
</p>
<textarea oninput="javascript:howBigAmI()" id="textarea">
how big am I?
</textarea>
<div id="output">size</div>
How can I get the current values?
(lineHeight property can’t be relied on unless I explicitly set it, so that’s not a solution.)
(I want to calculate how many rows are needed to show all of the textarea’s current content, if the width remains unchanged. But I don’t want to have to set either of the properties to be able to do the calculation.)
2
Answers
Can the "needed height" be in pixels, or you absolutely need it in "row units"?
If pixels are an option, use
el.scrollHeight
, like this:Perhaps there is a better option, but I still think that
line-height' should be used as a starting point. To do this, you need to calculate it in the current
`: