Categories
JavaScript Answers

How to set text area height automatically with JavaScript?

Spread the love

Sometimes, we want to set text area height automatically with JavaScript.

in this article, we’ll look at how to set text area height automatically with JavaScript.

How to set text area height automatically with JavaScript?

To set text area height automatically with JavaScript, we can create our own function to set the height when we type into the text area.

For instance, we write

const autoGrow = (e) => {
  e.target.style.height = "5px";
  e.target.style.height = e.target.scrollHeight + "px";
};

const textarea = document.querySelector("textarea");
textarea.oninput = autoGrow;

to create the autoGrow function that sets the height of the text area when we type in it.

We set style.height to change its height.

e.target is the text area since, we have

const textarea = document.querySelector("textarea");
textarea.oninput = autoGrow;

to listen for input events on the text area, which means autoGrow runs when we type in the text area.

Then we add the text area with

<textarea></textarea>

And we add

textarea {
  resize: none;
  overflow: hidden;
  min-height: 50px;
  max-height: 100px;
}

to disable resizing of the text area by the user with resize: none;.

Conclusion

To set text area height automatically with JavaScript, we can create our own function to set the height when we type into the text area.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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