Textarea autogrow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment