I am using the code from https://mcmap.net/q/74850/-textarea-auto-height-duplicate and modifying it for my question (mainly replacing element.style.height = "5px"
with element.style.height = "0px"
). My question is why do we even need to reset the textarea height before setting its height with its scrollHeight ?
function auto_grow(element) {
element.style.height = "0px"; // why do we even need this line ?
element.style.height = (element.scrollHeight)+"px";
}
<textarea oninput="auto_grow(this)"></textarea>
It does give weird behavior with this line element.style.height = "0px"
commented out as can be seen by running the code snippet below but what is causing this ? Does the scrollHeight attribute compute its value in a different way when the textarea height is not reset in the oninput handler ?
function auto_grow(element) {
console.log(`Before- ${element.scrollHeight}`);
// element.style.height = "0px";
element.style.height = (element.scrollHeight)+"px";
console.log(`After- ${element.scrollHeight}`);
}
<textarea
oninput="auto_grow(this)"></textarea>
console.log(element.scrollHeight)
right before and after updating the element height maybe you can have a better understanding of what's going on. – Martie