Skip to content

Instantly share code, notes, and snippets.

@stephenway
Forked from jlong/jquery.autogrow.js
Created March 19, 2012 22:56
Show Gist options
  • Save stephenway/2127959 to your computer and use it in GitHub Desktop.
Save stephenway/2127959 to your computer and use it in GitHub Desktop.
Autogrow Textareas in jQuery
/*
* jquery.autogrow.js
*
* A plugin written for UserVoice that makes it easy to create textareas
* that automatically resize to fit their contents.
*
* Based on Scott Moonen's original code for Prototype.js:
*
* <http://scottmoonen.com/2008/07/08/unobtrusive-javascript-expandable-textareas/>
*
* Author: John W. Long <john@uservoice.com>
*
*/
;(function($) {
$.fn.autogrow = function() {
return this.filter('textarea').each(function() {
if (!$(this).data('autogrow-applied')) {
var textarea = $(this)
, expander = $('<div />').css({'position': 'absolute', 'visibility': 'hidden', 'top': '-99999px'})
, escaper = $('<span />')
, properties = ['-webkit-appearance', '-moz-appearance', '-o-appearance', 'appearance', 'font-family', 'font-size', 'font-weight', 'font-style', 'border', 'border-top', 'border-right', 'border-bottom', 'border-left', 'box-sizing', 'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left', 'min-height', 'max-height', 'line-height']
, timer = null
;
$.each(properties, function(i, p) { expander.css(p, textarea.css(p)); });
$(textarea).after(expander);
function sizeTextarea() {
clearTimeout(timer);
timer = setTimeout(function() {
var value = escaper.text(textarea.val()).text().replace(/\n/g, '<br />') + '<br>z<br>z';
expander.html(value);
expander.css('width', textarea.innerWidth() + 'px');
textarea.css('height', expander.innerHeight() + 'px');
}, 100); // throttle by 100ms
}
textarea.bind('input.autogrow propertychange.autogrow', sizeTextarea)
sizeTextarea();
textarea.data('autogrow-applied', true);
}
});
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment