Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make the textarea resize just to top

I have a textarea that is a field for a person to type a message to be sent in a conversation (like whatsapp). But I need that when this textarea has more lines, it resizes only up, because if you resize down you end up exceeding the screen line and bugging the textarea. How can I do this?

Textarea:

          <div class="linha">
           <textarea style="resize: vertical;" type="text" (keydown)=search($event) (keyup)=keyup($event) [(ngModel)]="msg" #ctrl="ngModel" id="messageInput" rows="1" class="enter-message message-input linha"  placeholder=" Enter Message..."></textarea>
          </div>

OBS: Im using Angular.(I don’t know if it makes any difference)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

His current behavior:

enter image description here

>Solution :

You can use javascript to solve this problem:

const tx = document.getElementsByTagName("textarea");
for (let i = 0; i < tx.length; i++) {
  tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px; overflow-y:hidden;");
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput() {
  this.style.height = 0;
  this.style.height = (this.scrollHeight) + "px";
}
<textarea placeholder="Message...">Really long message with some content in it which makes it tall</textarea>
 <textarea style="resize: vertical;" type="text" (keydown)=search($event) (keyup)=keyup($event) [(ngModel)]="msg" #ctrl="ngModel" id="messageInput" rows="1" class="enter-message message-input linha"  placeholder=" Enter Message..."></textarea>

credits to @DreamTeK

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading