How to auto resize Textarea based on the input

My previous article was about “MongoDB and PHP tutorial for beginners”. Recently I came across a task to auto resize textarea based on the input. You may know textarea element doesn’t resize automatically as like other html elements, so I need to write a script to update the textarea height based on the content. I have done this using simple script which I would like to share with you.

Source Code:

Step 1:

Download jquery library or Google CDN library link. Include it into your web page.

Step 2:

I have fixed the minimum height to 50px. Paste below code into your html page.

<textarea id=”txtarea” class=”comment”></textarea>
<div id=”hidden-textarea-content” class=”comment hidden”></div>

<style type=”text/css”>
.comment {
    overflow: hidden;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word; 
.hidden {

Step 3:

Now paste below code to make our auto resizing to work.

<script type=”text/javascript”>

     var textarea = $(“#txtarea”), 
         clonedTextarea = $(“#hidden-textarea-content”), 
         content = null;

             textarea.on(“keyup focus keypress cut paste change keydown”, function() {
                  content = textarea.val();

                  clonedTextarea.css(“width”, textarea.width());
                  textarea.css(‘height’, clonedTextarea.height() + “px”);           



Step 4:

Finally run the page and you can see when you type content into textarea it's height will automatically change.

View Demo:

For a demo, you may have a look at my jsfiddle. Make sure before hit run before you test.


You can see this simple script will auto resize your textarea. You can still improve the script and also can make script into plugin. Hope this helps, if so please don’t forget to leave your comments, share and give a small like.
Keep visiting.

No comments:

Post a Comment

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 All rights reserved. Powered By- Sanjoy Dey Productions