Marko Anastasov wrote this on July 27, 2009

Google inspired autogrowing textareas with jQuery

There’s a post on Google Code blog which shows a snippet of Javascript to use to automatically grow a textarea field with input. Here’s a jQuery plugin kind of version of it. It is triggered after pasting as well, always hides the scrollbar and is able to determine the correct line height at run time. The GMail (mobile) team probably didn’t include it as an optimization measure.

jQuery.fn.grow = function() {
  this.each(function() {
    // attaching to change makes it paste-aware
    $(this).bind('keyup, change', function() {
      var textarea = $(this);
      // line-height is something like '12px', we need the number
      var lineHeight = $(textarea).css('line-height').split(/\D/)[0];
      var newHeight = $(textarea).attr('scrollHeight');
      var currentHeight = $(textarea).attr('clientHeight');

      if (newHeight > currentHeight) {
        $(textarea).css('overflow', 'hidden'); // prevent scrollbar appearance
        $(textarea).css('height', newHeight + 2 * lineHeight + 'px');
      }
    });
  });
}

To use it:

$("#post_body").grow();

What it doesn’t do is shrink as input is deleted and do some kind of animation. For that, you might want to check out the autogrow plugin. In our experience it doesn’t work with IE though. And it’s more code.

comments powered by Disqus

About Marko Anastasov

Marko co-founded Rendered Text. He’s a programmer with a passion of creating something for other people, coupled with interests in how things work in the society and nature. He is having a great time working across many areas in the company, including product design, helping the engineering teams, empowering users and marketing. He likes to counterbalance it all with running, cycling or a day in the woods.

Suggested Reads

Inject is a fundamental building block

Inject is one of the fundamental, and most versatile constructs available in functional languages. It can be used to implement map, select, max, all? and a bunch of other iteration related methods. Unfortunately, many programmers are not aware of its awesome powers. This article is here to improve this fact.

Contact

Rendered Text is a software company. For questions regarding Semaphore, please visit semaphoreci.com. Otherwise, feel free to get in touch any time by sending us an email.

Rendered Text
Svetozara Miletica 10
21000 Novi Sad
Serbia