Autogrow Textarea Using jQuery

Whenever we require to add some text that can be more than a line, we tend to use text area field on our web-forms. Its very to type a long content in text area instead of a input box. But let this go a step further, what if the text area field resize itself when we go to second line, or we press Enter to make a new line. And if there are lot of white space at the end of text it squeeze the text and trim end of the string removing the white spaces.

Okay, lets make it in some simple steps:

Add a text area to a simple HTML template

<textarea id="ExpandableTextarea"></textarea>

Now include jQuery from CDN or download it and include in your page in head section

 //use below link to get it from cdn
 http://code.jquery.com/jquery-1.8.3.min.js">http://code.jquery.com/jquery-1.8.3.min.js

Add a key press event in document scope. And under that check if user presses ‘Enter’ button by checking its key code 13. I am writing it only for a single text area on form, but if you want a restriction you can check in key press which text area is worked on.

//Here is an event to get TextArea expand when you press Enter Key in it.
// bind a key press event
$('textarea').keypress(function (e) {
  // check if user pressed 'Enter'
  if(e.which == 13) 
  {
    // get control object to modify further
    var control = e.target;
          
    // get existing 'Height' of pressed control
    var controlHeight = $(control).height();

    //add some height to existing height of control, I chose 17 as my line-height was 17 for the control 
    $(control).height(controlHeight+17);
  }
});

Add another event on blur to reduce its size if white space added by user.

// Now I am binding one more event "blur" on text area so to set it's height as per text when user focused out.
$('textarea').blur(function (e) {
     
    // Here we get exact number of lines in our text area
    var textLines = $(this).val().trim().split(/\r*\n/).length; 
 
    // Now apply the number Of Lines * line-height to your control. This is it.
    $(this).val($(this).val().trim()).height(textLines*17);
});


Here is complete fiddle for the process you would like to check it out.

Advertisements

One thought on “Autogrow Textarea Using jQuery

Say something : I accept all the "Humer&Critic"

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s