JSFiddle - React, Tailwind, and code Playground
by Kondal Durgam
HTML
<input class="autofit">
CSS
input {
min-width:200px;
width:200px;
max-width:200px;
resize:none;
font-size:18px;
overflow-x:hidden;
overflow-y:auto;
min-height:1.2em;
height:1.2em;
padding:2px;
max-height:5em;
position:absolute;
left:0px;
}
JavaScript
(function(){
var measurer = $('<span>', {
style: "display:inline-block;word-break:break-word;visibility:hidden;white-space:pre-wrap;"})
.appendTo('body');
function initMeasurerFor(textarea){
if(!input[0].originalOverflowY){
input[0].originalOverflowY = input.css("overflow-y");
}
var maxWidth = input.css("max-width");
measurer.text(input.text())
.css("max-width", input == "none" ? input.width() + "px" : maxWidth)
.css('font',textarea.css('font'))
.css('overflow-y', textarea.css('overflow-y'))
.css("max-height", textarea.css("max-height"))
.css("min-height", textarea.css("min-height"))
.css("min-width", textarea.css("min-width"))
.css("padding", textarea.css("padding"))
.css("border", textarea.css("border"))
.css("box-sizing", textarea.css("box-sizing"))
}
function updateTextAreaSize(textarea){
input.height(measurer.height());
var w = measurer.width();
if(textarea[0].originalOverflowY == "auto"){
var mw = textarea.css("max-width");
if(mw != "none"){
if(w == parseInt(mw)){
input.css("overflow-y", "auto");
} else {
input.css("overflow-y", "hidden");
}
}
}
input.width(w + 2);
}
$('input.autofit').on({
input: function(){
var text = $(this).val();
if($(this).attr("preventEnter") == undefined){
text = text.replace(/[\n]/g, "<br>​");
}
measurer.html(text);
updateTextAreaSize($(this));
},
focus: function(){
initMeasurerFor($(this));
},
keypress: function(e){
if(e.which == 13 && $(this).attr("preventEnter") != undefined){
e.preventDefault();
}
}
});
})();