Last active
January 20, 2016 07:11
-
-
Save nbubna/106abc060eeb62d1ee6a to your computer and use it in GitHub Desktop.
Vanilla JS textarea auto-size
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(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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI: this is adapted from my ongoing work here: https://github.com/esha/formx