Among the numerous StackOverflow examples showcasing an auto-height Textarea, one noteworthy example can be found here:
<textarea oninput="auto_grow(this)"></textarea>
textarea {
resize: none;
overflow: hidden;
min-height: 50px;
max-height: 100px;
}
function auto_grow(element) {
element.style.height = "auto";
element.style.height = (element.scrollHeight)+"px";
}
I am curious if there exists a similar solution that encompasses auto-width functionality in addition to auto-height?
Upon attempting to retrieve element.scrollWidth
, I noticed it kept returning the original width of the text area.
https://jsfiddle.net/on7zasd3/
EDIT:
After some experimentation, it seems like I may have cracked the code. (Although I am puzzled as to why the code formatting appears broken beyond this point on StackOverflow?)
I found it necessary to specify
cols="1"
for the text areaI also had to execute
and set the texture's width accordingly before initiating theelement.style.width = "auto";
auto
height adjustment.The Textarea also requires CSS property
white-space: nowrap;
:function auto_grow(element) { element.style.width = "auto"; console.log(element.scrollHeight+", "+element.scrollWidth) element.style.width = (element.scrollWidth)+"px";
element.style.height = "auto"; console.log(element.scrollHeight+", "+element.scrollWidth) element.style.height = (element.scrollHeight)+"px";
}
textarea { resize: none; overflow: hidden; min-height: 30px; min-width: 30px; white-space: nowrap; }