Skip to content

Instantly share code, notes, and snippets.

Created August 7, 2012 13:58
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Textarea autogrow
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';"hidden";"absolute";
function resize() {
// copy current textarea content = 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 = dv.offsetHeight + "px";
// resize right way if has some initial content
// resize onkeydown
textarea.addEventListener('keydown', resize, false);
textarea.addEventListener('input', resize, false);
textarea.addEventListener('propertychange', resize, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment