Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textarea to resize based on content length [duplicate]

Tags:

javascript

You can check the content's height by setting to 1px and then reading the scrollHeight property:

function textAreaAdjust(element) {
  element.style.height = "1px";
  element.style.height = (25+element.scrollHeight)+"px";
}
<textarea onkeyup="textAreaAdjust(this)" style="overflow:hidden"></textarea>

It works under Firefox 3, IE 7, Safari, Opera and Chrome.


You may also try contenteditable attribute onto a normal p or div. Not really a textarea but it will auto-resize without script.

.divtext {
    border: ridge 2px;
    padding: 5px;
    width: 20em;
    min-height: 5em;
    overflow: auto;
}
<div class="divtext" contentEditable>Hello World</div>

Use this function:

function adjustHeight(el){
    el.style.height = (el.scrollHeight > el.clientHeight) ? (el.scrollHeight)+"px" : "60px";
}

Use this html:

<textarea onkeyup="adjustHeight(this)"></textarea>

And finally use this css:

textarea {
min-height: 60px;
overflow-y: auto;
word-wrap:break-word
}

The solution simply is letting the scrollbar appears to detect that height needs to be adjusted, and whenever the scrollbar appears in your text area, it adjusts the height just as much as to hide the scrollbar again.


A jquery solution has been implemented, and source code is available in github at: https://github.com/jackmoore/autosize .


Alciende's answer didn't quite work for me in Safari for whatever reason just now, but did after a minor modification:

function textAreaAdjust(o) {
    o.style.height = "1px";
    setTimeout(function() {
        o.style.height = (o.scrollHeight)+"px";
    }, 1);
}

Hope this helps someone