JSFiddle - React, Tailwind, and code Playground
by mackry
HTML
<textarea id="text-area" rows="3" cols="50">asdsadasdas</textarea>
CSS
body {
margin: 20px;
}
textarea {
-webkit-transition: all 0.1s ease-out;
-moz-transition: all 0.1s ease-out;
-ms-transition: all 0.1s ease-out;
-o-transition: all 0.1s ease-out;
transition: all 0.1s ease-out;
resize: none;
}
JavaScript
$.fn.autogrow = function() {
this.filter('textarea').each(function() {
var $this = $(this),
minHeight = $this.height(),
shadow = $('<div></div>').css({
position: 'absolute',
top: -10000,
left: -10000,
width: $(this).width(),
fontSize: $this.css('fontSize'),
fontFamily: $this.css('fontFamily'),
lineHeight: $this.css('lineHeight'),
resize: 'none'
}).addClass('shadow').appendTo(document.body),
update = function() {
var t = this;
setTimeout(function() {
var val = t.value
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/\n/g, '<br/> ');
if ($.trim(val) === '') {
val = 'a';
}
shadow.html(val);
$(t).css('height', Math.max(shadow[0].offsetHeight + 20, minHeight));
}, 0);
};
$this.change(update).keyup(update).keydown(update).focus(update);
update.apply(this);
});
return this;
};
$(document).ready(function() {
$('textarea').autogrow();
});