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 )
};
}
Native Javascript solution without flickering in Firefox and faster than method withclientHeight...
1) Add
div.textarea
selector to all your selectors containingtextarea
. Do not forget to addbox-sizing: border-box;
2) Include this script:
Tested on IE11, Firefox and Chrome.
This solution creates div similar to your textarea including internal text and measures height.
jQuery solution adjust the css to match your requirements
css...
javascript...
OR alternative for jQuery 1.7+...
I've created a fiddle with the absolute minimum styling as a starting point for your experiments... http://jsfiddle.net/53eAy/951/
I used the following code for multiple textareas. Working fine in Chrome 12, Firefox 5 and IE 9, even with delete, cut and paste actions performed in the textareas.
You can use this piece of code to compute the number of rows a textarea needs:
Compute it on
input
andwindow:resize
events to get auto-resize effect. Example in Angular:Template code:
auto-wrap.directive.ts
Some of the answers here don't account for padding.
Assuming you have a maxHeight you don't want to go over, this worked for me:
If you don’t need to support IE8 you can use the
input
event:Now you only need to add some CSS and you are done:
Usage:
You can read more about how it works on my blog post.