Auto-expanding textarea

So you figure that you’ll make use of some of the new HTML5 goodness and improve the user experience for your website.  You can make those form elements look nice, but that horrible, horrible textarea (that was ugly in the early 90s and is still damned ugly) still mocks you by occupying needless space on your screen and being empty most of the time.

Wouldn’t it be nice for it to occupy a single row and then resize automatically as the user enters more text into it?

Well, if you don’t mind installing a jQuery plugin then James Padolsey has a working solution for you.

If you don’t mind sacrificing a bit of bling for something which you can understand and easily implement yourself, then try this solution that I worked out a few minutes ago:


<textarea id="myTextArea" rows="1" cols="20"
placeholder="Fill me up, buttercup."></textarea>


var ta = document.getElementById("myTextArea");
ta.addEventListener("scroll", function() {
 ta.setAttribute("rows", parseInt(ta.getAttribute("rows")) + 1);

That’s it.  No plugins.  No jQuery.  Just (if you optimise it) a single line of code.

Some people seem to think that the scroll event only fires when the player uses the scrollbars.  And since scrollbars are something that many of us turn off straight away, they disappear out of mind and out of sight… along with any approach that uses them.

What you may not know is that even if you hide scrollbars (using overflow-y:hidden or whatever) the scroll event still fires.  That means you can set up a listener for the event and then resize the textarea (by adding a row, for example) as soon as the user enters too much to fit unto the current area.

This simple approach has some drawbacks:

  • It doesn’t always add a single line, even though you expect it to.
  • It doesn’t collapse—so if a user deletes content, the text area won’t shrink.

Neither of these drawbacks concern me too much.  The first is a matter of preference anyway—I actually like having multiple lines inserted because it means that the element distracts me less often by resizing less frequently.  The second is also in the same boat—I prefer for a textarea, once expanded, to stay that way.

Minimising reflow is important to me.  If it’s not important to you then use the jQuery plugin mentioned earlier or roll your own solution.

(And yes, I know the song’s name is Build me up buttercup, no need to tell me.)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s