Skip to content

Instantly share code, notes, and snippets.

@kulakowka
Forked from navaru/gist:5779160
Created October 15, 2015 18:38
Show Gist options
  • Save kulakowka/8c6e7fe5007256477752 to your computer and use it in GitHub Desktop.
Save kulakowka/8c6e7fe5007256477752 to your computer and use it in GitHub Desktop.
Textarea auto-resize vanilla javascript (no jQuery plugin), for modern browsers
;(function () {
function domReady (f) { /in/.test(document.readyState) ? setTimeout(domReady,16,f) : f() }
function resize (event) {
event.target.style.height = 'auto';
event.target.style.height = event.target.scrollHeight+'px';
}
/* 0-timeout to get the already changed text */
function delayedResize (event) {
window.setTimeout(resize, 0, event);
}
domReady(function () {
var textareas = document.querySelectorAll('textarea[auto-resize]')
for (var i = 0, l = textareas.length; i < l; ++i) {
var el = textareas.item(i)
el.addEventListener('change', resize, false);
el.addEventListener('cut', delayedResize, false);
el.addEventListener('paste', delayedResize, false);
el.addEventListener('drop', delayedResize, false);
el.addEventListener('keydown', delayedResize, false);
}
})
}());
// Use: <textarea auto-resize></textarea>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment