Skip to content

Instantly share code, notes, and snippets.

@atinypixel
Created January 17, 2009 06:29
Show Gist options
  • Save atinypixel/48278 to your computer and use it in GitHub Desktop.
Save atinypixel/48278 to your computer and use it in GitHub Desktop.
Automatically grow your textarea inputs
// USAGE EXAMPLE (in HTML)
// <script type="text/javascript">
// new ResizingTextArea("dom_id_for_textarea_here");
// </script>
var ResizingTextArea = Class.create();
ResizingTextArea.prototype = {
defaultRows: 2,
initialize: function(field)
{
this.defaultRows = Math.max(field.rows, 2);
this.resizeNeeded = this.resizeNeeded.bindAsEventListener(this);
Event.observe(field, "click", this.resizeNeeded);
Event.observe(field, "keyup", this.resizeNeeded);
},
resizeNeeded: function(event)
{
var t = Event.element(event);
var lines = t.value.split('\n');
var newRows = lines.length + 1;
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(this.defaultRows, newRows);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment