0

I want a textarea to be like one in messengers. It a 1 line by default and becomes 2-4 lines when overflown with text.

Here's a piece of code for this:

function onInputHandle() {
    textarea.style.height = textarea.scrollHeight + "px";
}

And it works fine when the amount of lines should increase. But when I delete characters and don't need a new line anymore it works in a strange way.

Let's say a default height is 34px. Then it becomes 55px when expanded (a new line added).

But then I delete chracters so that I don't need that extraline anymore. And the textarea height is not immediately set to 34px. It decreases by 2px at a time - 53px, 53px and all the way down to 34px. Here's the logs:

// adding characters

textarea.style.height: 34px
textarea.scrollHeight: 34
------------------- 
textarea.style.height: 34px 
textarea.scrollHeight: 34 

// textarea overflown - new line added
-------------------
textarea.style.height: 55px
textarea.scrollHeight: 55
-------------------

// not overflown anymore after I deleted characters
// should be 34px, but decreasing by 2px instead
------------------- 
textarea.style.height: 53px
textarea.scrollHeight: 51
-------------------
textarea.style.height: 51px
textarea.scrollHeight: 49
------------------- 
textarea.style.height: 49px
textarea.scrollHeight: 47
-------------------
textarea.style.height: 47px
textarea.scrollHeight: 45
------------------- 
textarea.style.height: 45px
textarea.scrollHeight: 43
-------------------
textarea.style.height: 43px
textarea.scrollHeight: 41
------------------- 
textarea.style.height: 41px
textarea.scrollHeight: 39
-------------------
textarea.style.height: 39px
textarea.scrollHeight: 37
------------------- 
textarea.style.height: 37px
textarea.scrollHeight: 35
------------------- 
textarea.style.height: 35px
textarea.scrollHeight: 34
 ------------------- 
textarea.style.height: 34px
textarea.scrollHeight: 34
------------------- 
textarea.style.height: 34px
textarea.scrollHeight: 34 

const ta = document.querySelector(".ta");

ta.addEventListener("input", () => {
  console.log(`textarea.style.height: ${ta.offsetHeight}`);
  console.log(`textarea.scrollHeight: ${ta.scrollHeight}`);
  console.log("-------------------");
  ta.style.height = `${ta.scrollHeight}px`;
});
.ta {
/*   height: 34px; */
  resize: none;
}
<textarea class="ta"></textarea>
DarkBee
  • 16,592
  • 6
  • 46
  • 58
b3rry
  • 21
  • 5
  • added a link to codepen. But it won't help you much – b3rry Mar 07 '23 at 08:56
  • 1
    You forgot to take into account the default padding of the textarea. `scrollHeight` includes padding. – CBroe Mar 07 '23 at 09:19
  • @CBroe actually the trick was to reset the height and only after that I can assign new value to the height property – b3rry Mar 07 '23 at 23:03

0 Answers0