Created
January 17, 2009 06:29
-
-
Save atinypixel/48278 to your computer and use it in GitHub Desktop.
Automatically grow your textarea inputs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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