Skip to content

Instantly share code, notes, and snippets.

@marlun78
Last active October 6, 2015 08:28
Show Gist options
  • Save marlun78/2965416 to your computer and use it in GitHub Desktop.
Save marlun78/2965416 to your computer and use it in GitHub Desktop.
A jQuery plugin that converts a textarea to a auto-growing textarea
/**
* Autogrow, version 1.0
* Copyright (c) 2012, marlun78
* MIT License, https://gist.github.com/marlun78/bd0800cf5e8053ba9f83
*
* A jQuery plugin that converts a textarea to a (Facebook-like) auto-growing textarea.
* Built for jQuery 1.5.1
*/
$.fn.autogrow = function () {
var refresh = function (area, element) {
var br = '<br/>';
element.html(area.val().replace(/\n/g, br) + br);
area.height(element.height());
};
this.each(function () {
var area = $(this), shadow = null;
area.bind({
blur: function () {
shadow.remove();
},
focus: function () {
shadow = $('<div/>').css({
'border': area.css('border'),
'font-family': area.css('font-family'),
'font-size': area.css('font-size'),
'font-weight': area.css('font-weight'),
'line-height': area.css('line-height'),
'margin-top': '-999em',
'padding': area.css('padding'),
'position': 'absolute',
'width': area.width(),
'word-wrap': 'break-word'
}).appendTo($('body'));
refresh(area, shadow);
},
keyup: function () {
refresh(area, shadow);
}
});
area.css('overflow', 'hidden');
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment