Auto Resize Textarea Height using jQuery

Auto Resize feature makes a textarea more user-friendly. It expands the height of textarea automatically based on the content. If your web form contains a textarea, you can add the auto resize feature to resize height automatically to fit the content. In this tutorial, we will show you how to auto resize textarea using jQuery.

There are many third-party jQuery plugins are available to auto resize textarea height. But if you want to build your own script for textarea auto height feature, you can easily make textarea height auto adjustable using jQuery without any third-party plugin.

Our example code provides a simple way to add the auto-resize feature to textarea element using jQuery. When the content is inserted in the textarea, the height of the textarea field is expanded automatically based on the content. So, the textarea height will be fit to content and scrollbar not visible to the user.

Auto Resize Textarea

At first, include the jQuery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

HTML Code:
Add the textarea element which you want to auto resize.

<textarea id="content"></textarea>

JavaScript Code:
The following code makes the textarea element auto adjustable using jQuery.

  • On page load, a hidden clone DIV element is created and a class is added to textarea.
  • When the user starts typing, the textarea content is placed to the clone DIV.
  • The height of the clone DIV is applied to texrarea.
  • You need to specify the element selector (#content) in the textArea variable.
<script>
$(function(){
    var textArea = $('#content'),
    hiddenDiv = $(document.createElement('div')),
    content = null;
    
    textArea.addClass('noscroll');
    hiddenDiv.addClass('hiddendiv');
    
    $(textArea).after(hiddenDiv);
    
    textArea.on('keyup', function(){
        content = $(this).val();
        content = content.replace(/\n/g, '<br>');
        hiddenDiv.html(content + '<br class="lbr">');
        $(this).css('height', hiddenDiv.height());
    });
});
</script>

CSS Code:
The CSS takes an important part to make clone DIV invisible and hide the scrollbar.

<style>
textarea{
  width: 500px;
  min-height: 50px;
  font-family: Arial, sans-serif;
  font-size: 13px;
  color: #444;
  padding: 5px;
}
.noscroll{
  overflow: hidden;
  resize: none;
}
.hiddendiv{
  display: none;
  white-space: pre-wrap;
  width: 500px;
  min-height: 50px;
  font-family: Arial, sans-serif;
  font-size: 13px;
  padding: 5px;
  word-wrap: break-word;
}
.lbr {
  line-height: 3px;
}
</style>

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

1 Comment

  1. Nica Said...

Leave a reply

keyboard_double_arrow_up