Shrinky-Fit TextArea
While working on my latest hobby project, I wanted the text entry boxes to always be just large enough for the text you’re typing into them, similar to the text boxes in desktop apps like OmniFocus.
The first solution I found, jquery.autogrow, was not satisfactory. It simply did not respond to input quick enough to avoid having text slip out of the top of my input for a moment if I hit enter too fast, and it assumed you’d leave some space to write and not truly shrink to fit.
Wishing to replace it, I chatted with a friend and we came up with a scheme quite similar to another solution by Peter Michaux which I didn’t discover until after I threw together mine.
The gists of all of them are similar: take the text of your current textarea, place it in a similarly-styled div, let the browser flow it the way you want it, then apply its height back to the textarea.
My solution made a few little changes. Here’s the gist of it. I attached this as a keydown handler on the affected textareas. Each keydown, it copies the text into a similarly styled div, then sets the height like usual. Also, I used a zero-millisecond setTimeout so it would fire just after the textarea’s text was changed. I suppose I could have used bubbling up events instead. Not to be wasteful, my version only uses one doppelganger div for each different style of textarea I needed. Both are positioned absolutely at left:-9999999px.