Created
January 29, 2011 21:22
-
-
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
This file contains hidden or 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
/* | |
* 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); |
This file contains hidden or 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
$('.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 | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This solution is not bad. But I ended up doing my own for many reasons, explained here http://bit.ly/kBfnaD