Skip to content

Instantly share code, notes, and snippets.

@nbubna
Last active January 20, 2016 07:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbubna/106abc060eeb62d1ee6a to your computer and use it in GitHub Desktop.
Save nbubna/106abc060eeb62d1ee6a to your computer and use it in GitHub Desktop.
Vanilla JS textarea auto-size
(function(document) {
var flex = {
tagName: 'TEXTAREA',
attribute: 'autosize',
buffer: 20,
events: 'input propertychange change',
adjust: function(el, shrunk) {
var height = el.scrollHeight,
style = el.style;
if (height > el.offsetHeight - 2) {
style.height = (height+flex.buffer) + 'px';
} else if (!shrunk) {
style.height = '';
flex.adjust(el, true);
}
var width = el.scrollWidth;
if (width > el.offsetWidth) {
style.width = (width+flex.buffer) + 'px';
} else if (!shrunk) {
style.width = '';
flex.adjust(el, true);
}
}
};
flex.events.split(' ').forEach(function(type) {
document.addEventListener(type, function(e) {
var el = e.target;
if (el.tagName === flex.tagName && el.hasAttribute(flex.attribute)) {
flex.adjust(el);
}
});
});
})(document);
@nbubna
Copy link
Author

nbubna commented Nov 13, 2014

FYI: this is adapted from my ongoing work here: https://github.com/esha/formx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment