Skip to content

Instantly share code, notes, and snippets.

@helielson
Last active December 15, 2015 16:18
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save helielson/5287742 to your computer and use it in GitHub Desktop.
/*
* 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: webteam@jusbrasil.com.br
*/
;(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 before original textarea with the properties copied from
// original element
return this.$element.clone()
.removeAttr('id')
.removeAttr('name')
.css(propOb)
.attr('tabIndex','-1')
.insertBefore(this.$element);
},
init: function() {
var $clone = this.getClone(),
_this = this;
function resize () {
$clone.css('height', 'auto').val(_this.element.value);
_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