skip to Main Content

So I have a textarea

<textarea>
Very long content. Very long content. Very long content. 
Very long content. Very long content. Very long content. 
Very long content. Very long content. Very long content. 
Very long content. Very long content. Very long content. 
Very long content. Very long content. Very long content. 
Very long content. Very long content. Very long content. 
</textarea>

and I want to make the textarea fit the text in the textarea as the user type in it with the code below

const textarea = document.querySelector('textarea')
textarea.addEventListener('keyup', () => {
  textarea.style.height = `${textarea.scrollHeight}px`;
})

It works fine when the user add more text to the textarea. The problem is when the user clear the text inside and start typing again, the text area will not shrink to fit the text.

Any idea how to fix this?

2

Answers


  1. try this, it should shrink the textarea when value is empty:

    const textarea = document.querySelector('textarea')
    textarea.addEventListener('keyup', () => {
      textarea.style.height = textarea.value.length ? `${textarea.scrollHeight}px` : 'auto';
    })
    
    Login or Signup to reply.
  2. With this method, you can achieve what you want.

    function calcHeight(value) {
      let numberOfLineBreaks = (value.match(/n/g) || []).length;
      // min-height + lines x line-height + padding + border
      let newHeight = 20 + numberOfLineBreaks * 20 + 12 + 2;
      return newHeight;
    }
    
    let textarea = document.querySelector("textarea");
    textarea.addEventListener("keyup", () => {
      textarea.style.height = calcHeight(textarea.value) + "px";
    });
    

    You can also use span to create a textarea that has the result you want.

    HTML:

    <span class="textarea"></span>
    

    CSS:

    .textarea {
      border: 1px solid #ccc;
      font-family: inherit;
      font-size: inherit;
      padding: 1px 6px;
      display: block;
      width: 100%;
      overflow: hidden;
      resize: both;
      min-height: 40px;
      line-height: 20px;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search