orioltf
2/6/2013 - 10:42 AM

#JQUERY: Autoresize textarea. The textarea will resize itself automatically as you add/remov content. For sure can be improved! http://code

#JQUERY: Autoresize textarea. The textarea will resize itself automatically as you add/remov content. For sure can be improved! http://codepen.io/orioltf/pen/euImv

(function($) {
	$.fn.autoResizeTextarea = function() {
		return this.each(function() {
			if(this.tagName.toLowerCase() != "textarea") return;
			var rows = parseInt(this.getAttribute("rows"));
			if(rows < 2) this.setAttribute("rows", 2);
			else rows--;
			$(this).on('keyup', function() {
				var textLength = this.value.split("\n").length;
				if(rows < textLength) {
					console.log('1');
					this.setAttribute("rows", textLength+1);
				} else {
					console.log('2');
					this.setAttribute("rows", rows+1);
				}
			});
		});
	}
})(jQuery);
$('#comment').autoResizeTextarea();
<textarea id="comment" rows="0" cols="50"></textarea>