Skip to content

Instantly share code, notes, and snippets.

@stnvh
Last active August 29, 2015 14:23
Show Gist options
  • Save stnvh/3b55326bf602d1a14355 to your computer and use it in GitHub Desktop.
Save stnvh/3b55326bf602d1a14355 to your computer and use it in GitHub Desktop.
Adapts textarea rows to content length (opposed to a fixed height based approach) IE8+
(function() {
/* resize textarea based on text content (with IE8 support & no fixed heights or pseudo-divs!) */
// jquery
var textarea = $('textarea');
if(textarea.length) textarea.on('input propertychange', function() {
this.rows = ((this.value || '').match(/(\r?\n)/mg) || []).length + 1;
}).trigger('input');
// vanilla
var textarea = document.querySelectorAll('textarea'),
legacy = !('addEventListener' in window);
if(textarea.length) for(var i = 0; i < textarea.length; i++) {
textarea[i][legacy ? 'attachEvent' : 'addEventListener'].apply(textarea[i],
[legacy ? 'onpropertychange' : 'input', (function() {
var fnc = function(e) {
if(!e && legacy) e = window.event; var el = ('id' in this ? this : (e.target || e.srcElement));
el.rows = ((el.value || '').match(/(\r?\n)/mg) || []).length + 1;
}; fnc.apply(textarea[i], []);
return fnc;
})(), false]
);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment