Smart Area: A Lightweight Resizing Text Area Plugin for jQuery
November 14th, 2007Here’s a quick and dirty little jQuery plugin to create text areas that automatically resize.
I based it off of Richard McMahon’s Prototype Version
jQuery.fn.smartArea = function (){
return this.each(function() {
if (!jQuery(this).is("textarea")) {
return false;
}
jQuery(this).click( function(){
jQuery.SA.resizeArea( this ); } )
.keyup( function(){
jQuery.SA.resizeArea( this ); } );
return this;
});
}
jQuery.SA = {
resizeArea : function ( t ) {
var lines = t.value.split('\n') || [];
var newRows = lines.length;
var oldRows = t.rows;
for (var i = 0; i < lines.length; i++)
{ var line = lines[i]; if (line.length >= t.cols) newRows += Math.floor(line.length / t.cols);
}
if (newRows > t.rows) t.rows = newRows;
if (newRows < t.rows) t.rows = Math.max(1, newRows);
}
}


Previous Post
Next Post

7 Comments
July 28th, 2008 at 4:33 pm
How would I use this?
Not sure how to call the function
September 8th, 2008 at 9:02 am
thanks for the cool plugin!
mike, try something like this.
$(“textarea”).smartArea();
October 29th, 2008 at 7:35 pm
Do you have a demo installed somewhere for viewing?
April 23rd, 2009 at 5:38 pm
A handy addition to this is to add
.scroll(function(){ jQuery.SA.resizeArea( this ); } )
right after the .keyup line, so it will handle resizing when someone right-clicks and selects “paste”, causing scroll bars to appear.
April 24th, 2009 at 1:15 am
[...] I was having issues with a textarea resizer (a hacked-up version of SmartArea) that I had been using for a while in a work project. It was working fine for textareas of a [...]
June 29th, 2010 at 11:15 am
I was previously using the .autoResize() plugin, which is nice and even animates as the textareas resize, but unfortunately it cause other parts of my jquery form validation routine to not work ( see my question at http://stackoverflow.com/questions/3122008/jquery-autoresize-breaks-form-validation-for-textareas). Your smart area plugin totally fixed my problem! Thanks!
One note — in FF (I didn’t test this in other browsers before fixing it), scrollbars flicker on and off each time a new line is created. I added ‘overflow: hidden’ to my textareas’ css to prevent this.
June 30th, 2010 at 2:31 am
Great Catch, Thanks for adding this Josh.
Leave a Reply