Resizing Textareas as You Type with Prototype

May 27, 2009

In my last post I described how you can use jQuery to easily add dynamically scaling textareas to your site. Now here’s one for everyone using Rail’s standard javascript framework Prototype:

/*
 * Scale all textareas dynamically on the page
 * Requires Prototype
 */
function scaleTextareas(){
  $$('textarea').each(function(t){
      t.style.height = Math.floor($F(t).split('\n').inject(1, function(m, s){
        return m += (s.length/(t.offsetWidth/10)) + 1;
      })) + 8 + 'em';
    });
  setTimeout(scaleTextareas, 1000);
};
Event.observe(window, 'load', function() {
  scaleTextareas();
});

Its tested in Firefox, Safari, IE6 and IE7.

Here’s a demo and here’s the gist.