views:

455

answers:

3

Does anyone know of an actual, working jQuery plugin that can properly expand a textarea's height as text is added to it?

I have tried both the autogrow and growfield plugins and neither seem to work very well. Both have problems where they don't grow properly and/or ignore their max heights sometimes. I am using FF 3.5 on OSX for testing FWIW.

There was a third one that came up in Googling but that one's demo page didn't even work so I didn't bother trying it out.

A: 

I think this SA answer should help Not JQuery completely, but the code is small enough to implement on your own.

Scanningcrew
A: 

When working on my current project, I had a similar problem of just not being able to find a solid, reliable growing text area plugin. I ended up settling on growfield, but I can't say that I'm too happy with it.

One problem that I ran into that I was able to address was that growfield (in addition to almost every other plugin) insisted on adding an extra line to the text area at all times. This is rough development code, and currently only addresses Safari and Firefox, but here's some code I added to the end of growfield's getDummyHeight() function:

if ($.browser.safari) return h-sr.lh*2+sr.pt+sr.pb;
if ($.browser.mozilla) return h-sr.lh*2+sr.pt*2+sr.pb+5;

It uses browser detection (which is bad practice), and is probably dependent on our layout and CSS, but you might be able to do some tweaking to get it work well in your design.

In case you were wondering (growfield is a bit cryptic), h refers to the textarea height, sr.lh refers to the line height, sr.pt refers to the top padding and sr.pb refers to the bottom padding. The full list of variables is in the prepareSizeRelated() function.

Grant Heaslip
A: 

As with you, I've tried lots of jQuery solutions, but ended up coming back to plain old javascript every time. Assuming jQuery isn't an absolute requirement of yours, you could use something like the following (will need to adjust xxx to suit your particular textarea, should be ~1.3):

function resizeTextarea( textarea ) {
  currentRows = textarea.value.split('\n');
  newRows = 1;
  minRows = 4;

  for( i=0; i < currentRows.length; i++ ) {
    if( currentRows[i].length > textarea.cols ) {
      newRows += Math.ceil( currentRows[i].length / textarea.cols - xxx );
    }
  }

  newRows += currentRows.length;

  if( newRows != textarea.rows ) {
    textarea.rows = newRows;
  }
}
GlenCrawford