Is there anyway through CSS or Javascript set the height of the textarea based on the content? I have a hardcoded height in my CSS but i wanted it to default so there is no
I couldn't use scrollHeightas it return 0 on page load (maybe because my textarea is hidden on load).
Probably not nest practice (I am a newby in js) but the only option that worked was to count the number of lines in textarea and get length of the longer line in it. Then set the width and height accordingly.
var elements = document.getElementsByTagName("textarea")
for (var i = 0; i < elements.length; i++) {
var atagelement = elements[i];
console.log(atagelement.value);
var textareasplit =atagelement.value.split(/\r|\r\n|\n/);
var textareaheight = textareasplit.length *17 // change 17 according to your needs
var maxline=0
for (var j = 0; j < textareasplit.length; j++){
var line = textareasplit[j];
var linelenght= line.length;
if (maxline < linelenght){
maxline= linelenght;
};
};
var textareawidth= maxline*10 // change 10 according to your needs
atagelement.setAttribute('style', "width:" + textareawidth+"px ; height:"+textareaheight+"px");
}
If needed, you can also set max-width (or max-height) like this
var maxwidth= window.innerWidth *0.8
console.log(maxwidth)
atagelement.setAttribute('style', "width:" + textareawidth+"px ; height:"+textareaheight+"px ; max-width:" + maxwidth+ "px");