Clue Mediator

How to create an auto-resize Textarea in JavaScript

📅February 8, 2022

Here, you will learn how to create an auto-resize Textarea in JavaScript that will fit the content. In this article, we will discuss two different ways to automatically resize Textarea as you write content.

Checkout more articles on JavaScript

Method 1: Auto-resize Textarea as user types using JavaScript

In this method, we will use pure JavaScript to auto resize the textarea. For that, we have to use `input` addEventListener to resize the Textarea.





  <title>Auto-resize Textarea as user types using JavaScript - Clue Mediator</title>



  <textarea id="myTextarea" style="width: 500px;"></textarea>

  <script type="text/javascript">
    function autoResizeTextarea() {
      this.style.height = "auto";
      this.style.height = `${this.scrollHeight}px`;
    }

    var textareaEl = document.querySelector("#myTextarea");
    textareaEl.addEventListener('input', autoResizeTextarea, false);
  </script>

Method 2: Auto-resize Textarea to fit the content using jQuery

We can do the same example using jQuery. Check out the following jQuery example.





  <title>Auto resize the textarea to fit the content using jQuery - Clue Mediator</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>



  <textarea id="myTextarea" style="width: 500px;"></textarea>

  <script type="text/javascript">
    $('#myTextarea').on('input', function () {
      this.style.height = "auto";
      this.style.height = `${this.scrollHeight}px`;
    });
  </script>

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂