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.