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

5 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 [...]
Leave a Reply