Reset the height before Using scrollHeight
to expand/shrink the textarea correctly. Math.min()
can be used to set a limit on the textarea’s height.
Code:
var textarea = document.getElementById("textarea");
var heightLimit = 200; /* Maximum height: 200px */
textarea.oninput = function() {
textarea.style.height = ""; /* Reset the height*/
textarea.style.height = Math.min(textarea.scrollHeight, heightLimit) + "px";
};
Fiddle: http://jsfiddle.net/gjqWy/155
Note: The input
event is not supported by IE8 and earlier. Use keydown
or keyup
with onpaste
and/or oncut
if you want to support this ancient browser as well.