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 )
};
}
None of the answers seem to work. But this one works for me: https://coderwall.com/p/imkqoq/resize-textarea-to-fit-content
This works for me (Firefox 3.6/4.0 and Chrome 10/11):
If you want try it on jsfiddle It starts with a single line and grows only the exact amount necessary. It is ok for a single
textarea
, but I wanted to write something where I would have many many many suchtextarea
s (about as much as one would normally have lines in a large text document). In that case it is really slow. (In Firefox it's insanely slow.) So I really would like an approach that uses pure CSS. This would be possible withcontenteditable
, but I want it to be plaintext-only.For those who want the textarea to be auto resized on both width and height:
HTML:
CSS:
jQuery:
Codepen:
http://codepen.io/anon/pen/yNpvJJ
Cheers,
autosize
https://github.com/jackmoore/autosize
Just works, standalone, is popular (3.0k+ GitHub stars as of October 2018), available on cdnjs) and lightweight (~3.5k). Demo:
BTW, if you are using the ACE editor, use
maxLines: Infinity
: Automatically adjust height to contents in Ace Cloud 9 editorJust use
<pre> </pre>
with some styles like:Here is what I did while using MVC HTML Helper for TextArea. I had quite a few of textarea elements so had to distinguish them using Model Id.
and in script added this:
I have tested it on IE10 and Firefox23