2 * TextAreaExpander plugin for jQuery
4 * Expands or contracts a textarea height depending on the
5 * quatity of content entered by the user in the box.
7 * By Craig Buckler, Optimalworks.net
9 * As featured on SitePoint.com:
10 * http://www.sitepoint.com/blogs/2009/07/29/build-auto-expanding-textarea-1/
12 * Please use as you wish at your own risk.
18 * From JavaScript, use:
19 * $(<node>).TextAreaExpander(<minHeight>, <maxHeight>);
21 * <node> is the DOM node selector, e.g. "textarea"
22 * <minHeight> is the minimum textarea height in pixels (optional)
23 * <maxHeight> is the maximum textarea height in pixels (optional)
25 * Alternatively, in you HTML:
26 * Assign a class of "expand" to any <textarea> tag.
27 * e.g. <textarea name="textarea1" rows="3" cols="40" class="expand"></textarea>
29 * Or assign a class of "expandMIN-MAX" to set the <textarea> minimum and maximum height.
30 * e.g. <textarea name="textarea1" rows="3" cols="40" class="expand50-200"></textarea>
31 * The textarea will use an appropriate height between 50 and 200 pixels.
36 // jQuery plugin definition
37 $.fn.TextAreaExpander = function(minHeight, maxHeight) {
39 var hCheck = !($.browser.msie || $.browser.opera);
42 function ResizeTextarea(e) {
44 // event or initialize element?
47 // find content length and box width
48 var vlen = e.value.length, ewidth = e.offsetWidth;
49 if (vlen != e.valLength || ewidth != e.boxWidth) {
51 if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth)) e.style.height = "0px";
52 var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));
54 e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden");
55 e.style.height = h + "px";
65 this.each(function() {
68 if (this.nodeName.toLowerCase() != "textarea") return;
70 // set height restrictions
71 var p = this.className.match(/expand(\d+)\-*(\d+)*/i);
72 this.expandMin = minHeight || (p ? parseInt('0'+p[1], 10) : 0);
73 this.expandMax = maxHeight || (p ? parseInt('0'+p[2], 10) : 99999);
78 // zero vertical padding and add events
79 if (!this.Initialized) {
80 this.Initialized = true;
81 $(this).css("padding-top", 0).css("padding-bottom", 0);
82 $(this).bind("keyup", ResizeTextarea).bind("focus", ResizeTextarea);
92 // initialize all expanding textareas
93 jQuery(document).ready(function() {
94 jQuery("textarea[class*=expand]").TextAreaExpander();