Forums | MacLife
You are not logged in.
#1 2008-02-26 10:53 am
Auto-resizing textarea
Scholars,
I'm looking for a way to auto-resize a textarea based on the number of lines as wrapped by the textarea, regardless of font size or content type.
I'm looking to create a textarea that expands in the number of rows as the user types, e.g.:
Code:
+-----------------------------------+ |Hello, this is a textarea. | +-----------------------------------+ [Typing more...] +-----------------------------------+ |Hello, this is a textarea. But If I| |type... | +-----------------------------------+
Basically, I don't want to see scrollbars. And obviously I want the textarea to push on its parent element.
Thanks.
Basseq is me, John Whittet.
(Finishing the remainder of the thought expressed in the post has been left as an exercise for the reader.)
Offline
#2 2008-02-26 11:48 am
Re: Auto-resizing textarea
It's difficult. There is no perfect solution. What some sites (like Facebook) do is to create a hidden div with similar attributes (same font, width, etc.), set the div's contents to be the same as that of the textarea, read the clientHeight or whatever, and then set the textarea's height to that. The problem is that it isn't exact, so you really need a few buffer lines to account for any discrepancies. Another problem is that textareas and normal elements behave differently; for example, in some browsers (like Safari), long strings of non-space characters will wrap in a textarea, but will flow out the right side of a div. A third problem is that Safari seems to not like it when the user manually resizes the textarea, via handle, while a page script is also changing the textarea height.
Or you can just analyze the text and try to guess how many lines it will take up.
Another possible solution, one that I haven't explored, is to try using contentEditable mode on an element that will grow vertically to contain its contents.
Offline
#3 2008-02-27 8:10 pm
Re: Auto-resizing textarea
I think I thought of a solution, but I haven't tried it yet. Basically, forget the textarea. Grab the DOM node onclick, then add a handler such that every keystroke changes the content of the node. Of course, this kills paste... and isn't a great solution. Sort of mangles function for the sake of form.
Where in Facebook does this happen?
Basseq is me, John Whittet.
(Finishing the remainder of the thought expressed in the post has been left as an exercise for the reader.)
Offline
#4 2008-02-27 9:19 pm
Re: Auto-resizing textarea
Offline
