HTML TextArea resize automatically
If someone need a solution for Vue.js. Here is a vue directive to do a auto resizing text area. Just register directive globally once and you can use it for any textarea
Vue.directive('resizable', {
inserted: function (el) {
el.addEventListener('input', function(e) {
e.target.style.height = "auto";
e.target.style.height = e.target.scrollHeight + 'px';
});
}
});
html is easy, just put v-resizable attribute in textarea
<textarea v-resizable></textarea>
Special thanks to AniMir! I am using his input event handler.
If you are using AngularJS, you can do :
<textarea ng-keyup="ctl.handleTextAreaHeight($event)"></textarea>
With this in your controller :
this.handleTextAreaHeight = function (e) {
var element = e.target;
element.style.overflow = 'hidden';
element.style.height = 0;
element.style.height = element.scrollHeight + 'px';
};
In case anyone still needs this, for what it's worth, here's mine in pure js. But first, you may check this one: Auto expand a textarea using jQuery
var textAreas = document.getElementsByTagName('textarea');
try {
taLength = textAreas.length;
for (i=0; i < taLength; i++) {
var taId = textAreas[i].id;
document.getElementById(taId).addEventListener('input', function(e) {
e.target.style.height = "auto";
//This makes your textarea back to its original size. So you can replace it with any size you want it to have e.g. "120px"
//You may need some logic if you have multiple taxtareas with different original sizes
e.target.style.height = e.target.scrollHeight+'px';
});
}
}
catch (err) {
window.alert(err);
}
I used shubhra's answer to build that one. It is smooth and the scrollbar won't appear.
Resizing TeaxArea based on the content line number. Here's a DEMO
JS
function resizeTextarea (id) {
var a = document.getElementById(id);
a.style.height = 'auto';
a.style.height = a.scrollHeight+'px';
}
function init() {
var a = document.getElementsByTagName('textarea');
for(var i=0,inb=a.length;i<inb;i++) {
if(a[i].getAttribute('data-resizable')=='true')
resizeTextarea(a[i].id);
}
}
addEventListener('DOMContentLoaded', init);
HTML
<textarea id="InputTextArea" placeholder="placeholder" onkeyup="resizeTextarea('InputTextArea')"></textarea>