Skip to content

Instantly share code, notes, and snippets.

@mrofi
Last active August 29, 2015 14:19
Show Gist options
  • Save mrofi/a5c6bc25539eacf1750b to your computer and use it in GitHub Desktop.
Save mrofi/a5c6bc25539eacf1750b to your computer and use it in GitHub Desktop.
Autogrow Textarea with jQuery
// MIT Licence (MIT)
// Copyright (c) 2015 - Mokhamad Rofiudin
// inspired by Facebook Textarea
// Based on code here http://github.com/jackmoore/autosize
// The Magic Sauce : http://stackoverflow.com/a/3238543/4711810
// To Angular Go To Here https://gist.github.com/mrofi/e6a8656be9705652ff1f
(function($) {
$.fn.autogrow = function() {
return this.each(function() {
var textarea = this;
textarea.lineHeight = parseInt($(textarea).css("line-height"), 3);
$(textarea).data('oldValue', textarea.value);
$.fn.autogrow.sizeDown(textarea);
$(textarea).focus(function() {
textarea.interval = setInterval(function() {
if ($(textarea).data('oldValue').length < textarea.value.length) {
$.fn.autogrow.sizeUp(textarea);
} else if ($(textarea).data('oldValue').length > textarea.value.length) {
$.fn.autogrow.sizeDown(textarea);
}
$(textarea).data('oldValue', textarea.value);
}, 20);
}).blur(function() {
clearInterval(textarea.interval);
});
});
};
$.fn.autogrow.sizeUp = function(textarea) {
while(textarea.clientHeight < textarea.scrollHeight){
var height = textarea.clientHeight + textarea.lineHeight;
$(textarea).css("height", height);
}
};
$.fn.autogrow.sizeDown = function(textarea) {
do {
var height = textarea.clientHeight - textarea.lineHeight;
$(textarea).css("height", height);
} while(textarea.clientHeight >= textarea.scrollHeight)
$.fn.autogrow.sizeUp(textarea);
};
})(jQuery);
// Take this code in the wild
$('textarea').autogrow();
// See in the real world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment