Skip to content

Instantly share code, notes, and snippets.

@shankarcabus
Created November 5, 2013 17:21
Show Gist options
  • Save shankarcabus/7322665 to your computer and use it in GitHub Desktop.
Save shankarcabus/7322665 to your computer and use it in GitHub Desktop.
Textarea autoresize
/*
* jQuery autoresize 0.1
* http://jusbrasil.com
* Copyright 2013
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
* @author: [email protected]
*/
;(function ( $, window, document, undefined ) {
"use strict";
var pluginName = "autoresize",
defaults = {};
function Plugin( element, options ) {
this.element = element;
this.$element = $(element);
this.options = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
getClone: function() {
// The clone is necessary because when the height of the visible textarea is
// set as `auto`, the page height and the scrollTop changes. So, when the new
// height is set, depending of where is the cursor on screen, it disappears.
// So, the clone is used just to set the new height of the visible textarea.
// Properties which may effect space taken up by chracters:
var props = ['height','width','lineHeight','textDecoration','letterSpacing'],
propOb = {},
_this = this;
// Create object of styles to apply in the new HTML element
$.each(props, function(i, prop){
propOb[prop] = _this.$element.css(prop);
});
propOb = $.extend(propOb, {
position: 'absolute',
top: 0,
left: -9999
});
// Clone the actual textarea removing unique properties
// and insert after original textarea with the properties copied from
// original element
return this.$element.clone()
.removeAttr('id name class')
.css(propOb)
.attr('tabIndex','-1')
.addClass('autoresize-clone')
.insertAfter(this.$element);
},
init: function() {
var $clone = this.getClone(),
_this = this;
function resize () {
$clone.css('height', 'auto').val(_this.element.value);
var scrollHeight = $clone.get(0).scrollHeight;
scrollHeight && _this.$element.css('height', $clone.get(0).scrollHeight+'px');
}
/* 0-timeout to get the already changed text */
function delayedResize () {
window.setTimeout(resize, 0);
}
this.$element
.on('change', resize)
.on('cut paste drop keydown', delayedResize);
resize();
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment