public
Last active

Textarea autogrow

  • Download Gist
autogrow.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
function autogrow(textarea) {
// create fake div with same content
// (only works with box-sizing border-box)
var dv = document.createElement("div");
dv.className = 'fm-growable';
dv.style.visibility="hidden";
dv.style.position="absolute";
textarea.parentNode.appendChild(dv);
function resize() {
// copy current textarea content
dv.style.width = textarea.offsetWidth + 'px';
dv.innerHTML = textarea.value.replace(/\r\n|\n/g, "<br>");
dv.innerHTML += textarea.value[textarea.value.length-1] === '\n'? 'A' : ''; // trailing char if ends in \n
// set textarea size to be the same as the div
textarea.style.height = dv.offsetHeight + "px";
}
// resize right way if has some initial content
resize();
// resize onkeydown
textarea.addEventListener('keydown', resize, false);
textarea.addEventListener('input', resize, false);
textarea.addEventListener('propertychange', resize, false);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.