Skip to content

Instantly share code, notes, and snippets.

@kares
Created January 29, 2011 21:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kares/802204 to your computer and use it in GitHub Desktop.
Save kares/802204 to your computer and use it in GitHub Desktop.
simple jQuery plugin that allows textareas to grow vertically when text is typed in
/*
* Adapted from Autogrow Textarea Plugin
* @see http://www.technoreply.com/autogrow-textarea-plugin/
*/
(function($) {
$.fn.autoGrow = function() {
return this.each(function() {
var txtArea = $(this);
var colsDefault = txtArea.attr('cols');
var rowsDefault = txtArea.attr('rows');
var updateSize = function() {
var linesCount = 0;
var lines = txtArea.attr('value').split('\n');
for ( var i = lines.length - 1; i >= 0; --i ) {
linesCount += Math.floor( (lines[i].length / colsDefault) + 1 );
}
if ( linesCount >= rowsDefault ) {
txtArea.attr('rows', linesCount + 1);
}
else {
txtArea.attr('rows', rowsDefault);
}
};
txtArea.unbind('.autoGrow')
.bind('keyup.autoGrow', updateSize)
.bind('keydown.autoGrow', updateSize)
.bind('change.autoGrow', updateSize);
});
};
})(jQuery);
$('.js-auto-grow').live('keyup keydown change', function(evt) {
var $this = $(this);
var initAutoGrow = true;
var events = $this.data('events');
if (events) {
events = events.keyup || [];
for ( var i = 0, l = events.length; i < l; i++ ) {
if ( events[i].namespace === 'autoGrow' ) {
initAutoGrow = false; break;
}
}
}
if ( initAutoGrow ) {
$this.autoGrow();
$this.trigger(evt.type + '.autoGrow'); // re-trigger
}
});
@irae
Copy link

irae commented Jul 3, 2011

This solution is not bad. But I ended up doing my own for many reasons, explained here http://bit.ly/kBfnaD

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