Iago Alexandre
Iago Alexandre

Reputation: 473

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)

His current behavior:

enter image description here

Upvotes: 0

Views: 347

Answers (1)

Ramsey
Ramsey

Reputation: 114

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

Upvotes: 1

Related Questions