There was another thread about this, which I've tried. But there is one problem: the textarea
doesn't shrink if you delete the content. I can't find any way to shrink it to the correct size - the clientHeight
value comes back as the full size of the textarea
, not its contents.
The code from that page is below:
function FitToContent(id, maxHeight)
{
var text = id && id.style ? id : document.getElementById(id);
if ( !text )
return;
var adjustedHeight = text.clientHeight;
if ( !maxHeight || maxHeight > adjustedHeight )
{
adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
if ( maxHeight )
adjustedHeight = Math.min(maxHeight, adjustedHeight);
if ( adjustedHeight > text.clientHeight )
text.style.height = adjustedHeight + "px";
}
}
window.onload = function() {
document.getElementById("ta").onkeyup = function() {
FitToContent( this, 500 )
};
}
Has anyone considered contenteditable? No messing around with scrolling,a nd the only JS I like about it is if you plan on saving the data on blur... and apparently, it's compatible on all of the popular browsers : http://caniuse.com/#feat=contenteditable
Just style it to look like a text box, and it autosizes... Make its min-height the preferred text height and have at it.
What's cool about this approach is that you can save and tags on some of the browsers.
http://jsfiddle.net/gbutiri/v31o8xfo/
I know a short and correct way of implementing this with jquery.No extra hidden div needed and works in most browser
Tested in Firefox 14 and Chromium 18. The numbers 24 and 12 are arbitrary, test to see what suits you best.
You could do without the style and script tags, but it becomes a bit messy imho (this is old style HTML+JS and is not encouraged).
Edit: modernized code. Changed onkeyup attribute to addEventListener.
Edit: keydown works better than keyup
Edit: declare function before using
Edit: input works better than keydown (thnx @WASD42 & @MA-Maddin)
jsfiddle
You can use this code:
Coffescript:
Javascript
MakeTextAreaResisable that uses qQuery
A COMPLETE YET SIMPLE SOLUTION
Updated 23/08/2017 (Improved browser support for mobiles and tablets)
The following code will work:
OPTION 1 (With jQuery)
This code requires jQuery and has been tested and is working with 1.7.2 - 3.2.1
Simple (Add this jquery code to your master script file and forget about it.)
Test on jsfiddle
OPTION 2 (Pure JavaScript)
Simple (Add this JavaScript to your master script file and forget about it.)
Test on jsfiddle
OPTION 3 (jQuery Extension)
Useful if you want to apply further chaining to the textareas you want to be auto-sized.
Invoke with
$('textarea').autoHeight()
UPDATING TEXTAREA VIA JAVASCRIPT
When injecting content into a textarea via JavaScript append the following code to invoke the function in option 1.