Skip to content

Instantly share code, notes, and snippets.

@robozevel
Created November 15, 2012 02:21
Show Gist options
  • Save robozevel/4076237 to your computer and use it in GitHub Desktop.
Save robozevel/4076237 to your computer and use it in GitHub Desktop.
Auto-Resizing Textareas for jQuery
/**
* Auto-Resizing Textareas (jQuery v1.7+)
* Based on: http://phaistonian.pblogs.gr/expanding-textareas-the-easy-and-clean-way.html
*
* Usage:
* // Direct binding
* $("textarea").autoResize();
*
* // Delegated binding
* $.autoResize("textarea");
* $(".container").autoResize("textarea");
*
**/
;(function($) {
"use strict";
var events = "oninput" in window ? "input" : "keyup keydown";
function resize() {
this.style.height = "auto";
this.style.height = this.scrollHeight + this.offsetHeight - this.clientHeight + "px";
}
function autoResize(element, selector) {
var $element = $(element);
if (typeof selector !== "string") {
selector = null;
$element = $element
.filter("textarea")
.attr("rows", 1)
.css({
"resize" : "none",
"overflow-y": "hidden"
})
.each(resize);
}
return $element.on(events, selector, resize);
}
$.autoResize = function(selector) {
return autoResize(document, selector);
};
$.fn.autoResize = function(selector) {
return autoResize(this, selector);
}
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment