I\'m trying to do a simple auto-expanding textarea. This is my code:
textarea.onkeyup = function () {
textarea.style.height = textarea.clientHeight + \'px\
For those interested in a jQuery version of Rob W's solution:
var textarea = jQuery('.textarea');
textarea.on("input", function () {
jQuery(this).css("height", ""); //reset the height
jQuery(this).css("height", Math.min(jQuery(this).prop('scrollHeight'), 200) + "px");
});
using
<div contentEditable></div>
may also do the same work, expanding it self, and requires no js
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.
...and if you need an infinitely expanding textarea (as I did), just do this:
var textarea = document.getElementById("textarea");
textarea.oninput = function() {
textarea.style.height = ""; /* Reset the height*/
textarea.style.height = textarea.scrollHeight + "px";
};
I've wanted to have the auto-expanding area to be limited by rows number (e.g 5 rows). I've considered using "em" units, for Rob's solution however, this is error-prone and wouldn't take account stuff like padding, etc.
So this is what I came up with:
var textarea = document.getElementById("textarea");
var limitRows = 5;
var messageLastScrollHeight = textarea.scrollHeight;
textarea.oninput = function() {
var rows = parseInt(textarea.getAttribute("rows"));
// If we don't decrease the amount of rows, the scrollHeight would show the scrollHeight for all the rows
// even if there is no text.
textarea.setAttribute("rows", "1");
if (rows < limitRows && textarea.scrollHeight > messageLastScrollHeight) {
rows++;
} else if (rows > 1 && textarea.scrollHeight < messageLastScrollHeight) {
rows--;
}
messageLastScrollHeight = textarea.scrollHeight;
textarea.setAttribute("rows", rows);
};
Fiddle: http://jsfiddle.net/cgSj3/