Those handy little webdevelopment things

dinsdag 13 mei 2008

Auto resize / growing Textarea

Sometimes it's nice to have a Textarea autosize to it's content, therefore I used the solution of Marko Samutur (http://markos.gaivo.net/blog/?p=198), but I found the way of expanding a bit to static (and missing decreasing height), therefore I changed his code a little bit:
function grow() {
// Opera isn't just broken. It's really twisted.
if (this.scrollHeight > this.clientHeight && !window.opera)
this.rows += 1;
}
Became:
function grow(control, minimumRows) {                 
control.rows = minimumRows;
if(control.scrollHeight > control.clientHeight)
{
// Grow till it fits
while(control.scrollHeight > control.clientHeight)
{
control.rows += 1;
}
}
}
Two parameters, one submitting the control itself (this) and one giving the minimum amount of rows to know how far to shrink. This way it grows until it fits, for example after a paste more than 1 line might have been added at once. I also add the grow() call to 'onfocus' and 'onblur' to be even more sure the size is correct. And because the Textarea is first reset to it's initial size by the minimumRows parameter it will also decrease.

Decreasing / shrinking is dirty
Until now I haven't found a pretty way to decrease the Textarea as I can't find any way to measure this.

Have fun using this and post any comments to make this even better!