JSFiddle - React, Tailwind, and code Playground
HTML
<textarea id="txt1" autoHeight></textarea>
<br/>
<textarea autoHeight>With initial text
rgrgdggdfgfg</textarea>
CSS
#txt1{
width: 250px;
}
JavaScript
var applyAutoSize = function(){
var $hDiv;
var resize = function(){
var $this= $(this),
width = $this.width(),
text= $this.val(),
modifText;
// prevent really thin textareas
if(text === "")
modifText= "|";
else
modifText = text;
// replace CR with <br/>
modifText = modifText.replace(/(\r\n|\n|\r)/g,"<br/>");
// setup the hidden div
$hDiv
.css('font-family', $this.css('font-family'))
.html(modifText)
.width(width);
// pick the hidden div height and set it to the textarea
$this.height($hDiv.height());
};
var init = function(){
var $txt = $('textarea[autoHeight]');
// dynamically add the hidden div
$hDiv = $('div#__autoHeight');
if($hDiv.length === 0){
$hDiv = $('<div id="__autoHeight" style="display:none;word-wrap: break-word;padding: 3px;"></div>');
$('body').append($hDiv);
}
$txt.css('overflow', 'hidden');
$txt.each(function(idx,item){
resize.call(item);
});
// capture all events
$txt.on('change keyup keydown paste', function(){
resize.call(this);
});
};
init();
}
applyAutoSize();