ResizingTextArea Prototype Component

Written by on January 16th, 2007 in Ajax News.

Richard McMahon has wrapped the oft-seen resizable text areas in a simple Prototype component ResizingTextArea:

JavaScript

JAVASCRIPT:

  1.  
  2. var ResizingTextArea = Class.create();
  3.  
  4. ResizingTextArea.prototype = {
  5.     defaultRows: 1,
  6.  
  7.     initialize: function(field)
  8.     {
  9.         this.defaultRows = Math.max(field.rows, 1);
  10.         this.resizeNeeded = this.resizeNeeded.bindAsEventListener(this);
  11.         Event.observe(field, “click”, this.resizeNeeded);
  12.         Event.observe(field, “keyup”, this.resizeNeeded);
  13.     },
  14.  
  15.     resizeNeeded: function(event)
  16.     {
  17.         var t = Event.element(event);
  18.         var lines = t.value.split(’\n’);
  19.         var newRows = lines.length + 1;
  20.         var oldRows = t.rows;
  21.         for (var i = 0; i <lines.length; i++)
  22.         {
  23.             var line = lines[i];
  24.             if (line.length>= t.cols) newRows += Math.floor(line.length / t.cols);
  25.         }
  26.         if (newRows> t.rows) t.rows = newRows;
  27.         if (newRows <t.rows) t.rows = Math.max(this.defaultRows, newRows);
  28.     }
  29. }
  30.  

UJS Rule

HTML:

  1.  
  2. <% apply_behaviour “textarea”, “new ResizingTextArea(this);” %>
  3.  

It responds to keystrokes by parsing the text value into lines, accounts for a bit of line wrapping, and ensures that the number of rows presented grows (and shrinks) to match what has been typed in. The solution is best suited where the text entry is likely to be in the 0-50 line range.

Source: Ajaxian
Original Article: http://ajaxian.com/archives/resizingtextarea-prototype-component

Leave a Reply

You must be logged in to post a comment.



Site Navigation