Textarea increase according to text

Asked

Viewed 1,901 times

3

//However 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>

  • Unused function? explain that

  • Taking only by the textarea ex: <textarea></<textarea> || without using the Function inside ... I don’t know how to understand ?

  • This I understood, but why without using function?

  • because here this textarea is generated automatically, it comes without id and without onkeydown

  • And even with the function no problem at all

  • You won’t have a problem

Show 1 more comment

2 answers

4


Without using function, you can place Javascript directly in the element with oninput:

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

Or else create a Listener for all the textarea that have a specific class. In the example below, it will only have the effect of 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>

  • Vallleeew That’s what it was ;-)

2

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

You can use the this and change the function as below:

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

  • I think he wants without using function, I just don’t understand why

  • without onkeydown="autoResize()", all direct by javascript without putting any tag in html I don’t know if I understand !

  • Got it, it would be the DVD response then.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.