Skip to content

Instantly share code, notes, and snippets.

@davidcorbin
Created January 19, 2015 15:56
Show Gist options
  • Save davidcorbin/e1440b2037de6d3e024d to your computer and use it in GitHub Desktop.
Save davidcorbin/e1440b2037de6d3e024d to your computer and use it in GitHub Desktop.
Autoresize textarea
var observe;
if (window.attachEvent) {
observe = function (element, event, handler) {
element.attachEvent('on'+event, handler);
};
}
else {
observe = function (element, event, handler) {
element.addEventListener(event, handler, false);
};
}
function autoresize(element) {
//var text = document.getElementsByTagName('textarea')[0];
function resize () {
element.style.height = 'auto';
element.style.height = element.scrollHeight+'px';
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
observe(element, 'change', resize);
observe(element, 'cut', delayedResize);
observe(element, 'paste', delayedResize);
observe(element, 'drop', delayedResize);
observe(element, 'keydown', delayedResize);
element.focus();
element.select();
resize();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment