I'm trying to make a simple auto-expanding text area. This is my code:
textarea.onkeyup = function () { textarea.style.height = textarea.clientHeight + 'px'; }
But the text area will grow infinitely as you type...
I know there are Dojo and jQuery plugins for this, but I don't want to use them. I looked at their implementation and originally usedscrollHeight
but did the same thing.
You can start answering and use the text area to play your answer.
I want the auto-expand area to be limited by the number of rows (e.g. 5 rows). I considered using "em" units, forRob's solution, however, this iserror-proneand doesn't take into account stuff like padding.
This is my idea:
Fiddle:http://jsfiddle.net/cgSj3/
Reset the height before correctly expanding/shrinking the text area using
scrollHeight
.Math.min()
Can be used to set the height limit of the text area.Code:
Fiddle:http://jsfiddle.net/gjqWy/155
Note:
input
events are not supportedin IE8 and earlier. If you also want to support this ancient browser, please usekeydown
orkeyup
andonpaste
and/oroncut
.