I'm having a bit of trouble with some code I put into a page. I want to have every textarea element auto-grow when altered and auto-resize when the page first loads. The code I've got is as follows:
function auto_grow(element) {
element.style.height = '5px';
element.style.height = (element.scrollHeight) + 'px';
console.log(element + ' changed to ' + element.style.height);
}
window.addEventListener('load', function () {
var e = document.getElementsByTagName('textarea');
for (var i = 0; i < e.length; i++) {
auto_grow(e[i]);
e[i].addEventListener('change', function () {
auto_grow(e[i])
});
}
})
It resizes on load with no problems, but not on change. I assume I'm missing something simple, but I can't work out what it is. Can anyone shed some light on what I'm missing?
edit: based on the input received, I came up with the following solution that works for me:
window.addEventListener("load", function () {
var e = document.getElementsByTagName('textarea');
var a = Array.prototype.slice.call(e,0);
a.forEach(function(x) {
auto_grow(x);
x.addEventListener("keyup", function(){auto_grow(this)});
})
}
)
I used keyup
as it seemed to be more consistent. forEach
reminded me more of the iterative loops I'm used to from python, so I went with that option instead others.