Textarea increase as text

3

// But without using function and picking up more than one TEXTAREA

 function autoResize()
    {
        objTextArea = document.getElementById('txtTextArea');
        while (objTextArea.scrollHeight > objTextArea.offsetHeight)
        {
            objTextArea.rows += 1;
        }
    }
<textarea id="txtTextArea" onkeydown="autoResize()"></textarea>
    
asked by anonymous 21.11.2017 / 19:00

2 answers

4

Without using function, you can put JavaScript directly on the element with oninput :

<textarea oninput='if(this.scrollHeight > this.offsetHeight) this.rows += 1'></textarea>

Or create a listener for all textarea that have a specific class. In the example below, it will only have the effect textarea with class .autoTxtArea :

var txtAreas = document.querySelectorAll('.autoTxtArea');
for(x=0;x<txtAreas.length;x++){
   txtAreas[x].addEventListener('input', function(){
        if(this.scrollHeight > this.offsetHeight) this.rows += 1;
   });
}
<textarea placeholder="Com efeito" class="autoTxtArea" id="txtTextArea"></textarea>
<br />
<textarea placeholder="Sem efeito" id="txtTextArea"></textarea>
    
21.11.2017 / 19:13
2

I believe that what you want is to do without associating only one element as it is within the function by taking the element by id .

You can use this and change function as below:

function autoResize(el){
  while (el.scrollHeight > el.offsetHeight){
    el.rows += 1;
  }
}
<textarea onkeydown="autoResize(this)"></textarea>
<textarea onkeydown="autoResize(this)"></textarea>
    
21.11.2017 / 19:04