A pure javascript solution for automatically growing textarea
element on typing.
- Works in all cases: expands on line breaks and word breaks.
- Great Performance: minimal DOM manipulation.
- Allows limitation of growing so a scrollbar will appear after X lines of content.
A full explanation of the code can be found on my blog post along with a jQuery plugin and an Angular directive with this technique.
bower install textarea-autogrow
npm install textarea-autogrow
Just include textarea-autogrow.js
file in <head>
tag or require it:
<script type="text/javascript" src="textarea-autogrow.js"></script>
var Autogrow = require('textarea-autogrow');
Then initialize the magic:
var textarea = document.getElementById('myTextarea');
var growingTextarea = new Autogrow(textarea);
It's also recommended to add those two CSS properties to make things stable:
#myTextarea {
resize: none;
box-sizing: content-box;
}
Just place a second argument on initialization:
var growingTextarea = new Autogrow(textarea, 3); // up to 3 lines height
You can set the initial row number using simple HTML attribute rows
:
<textarea id="myTextarea" rows="1"></textarea>