Categories
JavaScript Answers

How to Text Area to Resize Based on Content Length with JavaScript?

Spread the love

Sometimes, we want to resize a text area to wrap around all the content inside with JavaScript.

In this article, we’ll look at how to resize a text area to wrap around all the content inside with JavaScript.

Set the Height of the Text Area to the Scroll Height

The scrollHeight property of the text area element has the full height of the content in pixels.

Therefore, we just need to set the height of the text area to the scroll height to set the height of the text area to wrap around all the content of the text area.

For instance, if we have the following HTML:

<textarea></textarea>

Then we can get the text area and then set the height to the scroll height by writing:

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

We get the text area with document.querySelector .

Then we call addEventListener with 'keyup' as the first argument to add a keyup listener for the text area.

In the event listener, we set the style.height to textarea.scrollHeight to set the height of the text area to the height of the content inside.

We should remember to include the unit so that the height will be set.

Now when we type into the text area, it’ll resize the height to wrap around all the content.

Conclusion

We can set the height of the text area to the scroll height to set the height of the text area to wrap around all the content of the text area.

Leave a Reply

Your email address will not be published. Required fields are marked *