Auto-Grow Textarea – doing it the easy way in Javascript

Text boxes can hold an unlimited amount of text (except where you use a Javascript to limit the input). Normally the textarea has (or acquires) scrollbars when the amount of text is too large to display in the defined area. If you are using a recent version of Internet Explorer or Netscape 6+ then the following text area will not use scrollbars, instead the textarea itself will grow to accomodate the amount of text that is entered into the field.

Note that this script doesn’t resize the text area in Netscape 4 or Opera 5/6. With Opera 7 the insertion point is unfortunately reset to the start of the field whenever the field gets resized but this was fortunately fixed in Opera 8 and the number of people still using Opera 7 is probably too low to worry about. With browsers (except for Opera 7) that don’t handle resizing the field properly it will behave normally with scrollbars.

So how do we get the textarea to resize itself on those browsers that can handle it? Well first we place the following Javascript into the head section of the page:

function sz(t) {
a = t.value.split(‘\n’);
for (x=0;x < a.length; x++) { if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
b+= a.length;
if (b > t.rows) t.rows = b;

Then all we need to do is to add onkeyup=”sz(this);” to the textarea parameters to get the size of the textarea to be recalculated each time the content of the textarea is changed.

Note that the code is set up to make the textarea bigger whenever the content will not fit, the code tests if the calculated size is less than the existing size of the field and where that is the case the field is left alone. The code tests both for new line characters in the field content as well as text between new line characters that is too long to fit the textarea width and which will therefore wrap onto extra lines so regardless of what is entered into the field it should grow to allow the field content to be displayed without the need for scrollbars in most cases.

Because of the way that the browsers may wrap the field content early because the next word will not fit onto the end of the line there may be occasions where the textarea does not grow sufficiently to display the entire content but even in these rare cases all but one or two lines should be visible.

Of course reloading the page will reset the size of the text area back to its default size. The textarea(s) will automatically resize themselves back to the larger size when they get the focus via the keyboard. If you want the field to resize itself when it gets the focus via a mouse click as well, add onclick=”sz(this);” to the textarea tag.
Author: Stephen Chapman