Automatically Expanding Textarea Elements with Yahoo! UI
The usual method
A textarea element must have rows and cols attributes. These specify the number of monospace characters that can fit down and across the textarea. The method for automatically expanding a textarea that I have seen in other tutorials depends on the rows and cols attributes. The number of characters in the textarea divided by the number of columns equals the number of needed rows. This is fine for monospaced fonts.
When proportionally spaced fonts, with their very skinny 'i' and 'l' characters, are used inside a textarea the method just described falls apart. Since each 'i' doesn't use up it's alloted width in the calculation more rows are calculated than are needed. This example shows the problem in an exaggerated way. Try changing most of the characters to a wide character like 'M'. The excess whitespace problem is not present. (Note, I didn't make much effort in getting this example working nicely with scrollbars etc. This method was a dead end path for me.)
A new method
Instead of calculating the number of rows needed I took a totally different approach. Into the document I inserted a hidden div with the same width and font as the textarea. I did this for each text area. I cloned the contents of the textarea into this hidden div. This div naturally resizes to the correct height needed. I used
YAHOO.util.Dom.getRegion() to calculate the height of the div. I then assigned this height (plus one and a half extra rows worth of height) to the textarea. Using
setTimeout() I repeat this process every 300 ms or so. The extra one and a half rows makes the user experience nicer when adding to the bottom of the textarea. If they add enough that another row is needed then it is already there for them. They don't have to wait for the current timeout to expire before the textarea is expanded large enough to contain the contents.
Note: This is definitely a hack and it works with reasonable input. Words wider than the textarea will likely cause undesireable results. This is not likely to be a big problem in real applications.
Have something to write? Comment on this article.