2

I'm trying to dynamically change the height of the textarea element but my code isn't working as expected.

What should happen:

As a new line appears, the textarea's height increases until it reaches its max height.

As you remove lines the textarea's height decreases until it reaches its min height.

What is happening:

The height increases as new lines are added but the textarea doesn't behave as expected when removing lines. It decreases much more slowly and doesn't reach the min height.

let textInput = document.querySelector(".text-input");

textInput.addEventListener('input', function() {
  textInput.style.height = 'auto';
  textInput.style.height = textInput.scrollHeight + 'px';
});
.text-input {
  width: 100%;
  max-height: 250px;
  min-height: 100px;
  resize: vertical;
  box-sizing: border-box;
}
<textarea class="text-input"></textarea>

Edit

from the link posted. A simple fix is to add the following line

  textInput.style.height = textInput.scrollHeight + 'px';

0 Answers0