Daniels Jirgensons Daniels Jirgensons - 1 month ago 15
jQuery Question

Expanding multiple textareas with JQuery

Im new with JQuery or Javascript, but I dont know why ,only one of my textarea expands, but other not. I found this code, but I dont know, how to fix this problem. You can test this in my JSFiddle

There is the JQuery

var textarea = document.querySelector('.text1, .text2');

textarea.addEventListener('keydown', autosize);

function autosize(){
var el = this;
setTimeout(function(){
el.style.cssText = 'height:auto; padding:0';
el.style.cssText = 'height:' + el.scrollHeight + 'px';
},0);
}

Answer

Use document.querySelectorAll() to get a list of elements and then iterate to bind the event handler.

var textarea = document.querySelectorAll('.text1, .text2');
for (var i = 0; i < textarea.length; i++) {
  textarea[i].addEventListener('keydown', autosize);
}

Fiddle

Comments