Kung Fu Kung Fu

Fujian White Crane Kung Fu

Zope Zope

What I have and am doing with Zope

Photos Photos

Photoalbum, both old and new.

Receptsamlingen Receptsamlingen

In Swedish only. About my "Collection of Recipes" website.

Contact me Contact me

My contact details and how to contact me.

  Mobile version of this page Mobile version of this page


 

Vertically expanding textarea input boxes

vertically, textarea, grows, textareas, hardlines, autoexpanding, linebreaks, linebreak

18th of September 2007

I've recently improved the IssueTrackerProduct so that when you start to write in the little textarea it expands and grows vertically as the text gets larger and larger. Other sites like Highrise do this too for note taking.

Long story short, here's the demo and here's the solution:

 function _getNoLines(element) {
   var hardlines = element.value.split('\n');
   var total = hardlines.length;
   for (var i=0, len=hardlines.length; i<len; i++) {
      total += Math.max(Math.round(hardlines[i].length / element.cols), 1) - 1;
   }
   return total;
 }

 $(function() {

   // First, for all the textareas that have lots of lines of text 
   // in them, we want to double their number of rows
   $('textarea.autoexpanding').each(function() {
      while (_getNoLines(this) > parseInt(this.rows))
        this.rows = '' + Math.round((parseInt(this.rows) * 1.5));
   });

   // When a user enters new lines, if they have entered more
   // lines than the textarea has rows, then double the textareas rows
   $('textarea.autoexpanding').bind('keyup', function() {
      if (_getNoLines(this) > parseInt(this.rows))
        this.rows = '' + Math.round((parseInt(this.rows) * 1.5));
   });

 }

How you deploy this obviously depends on your context and application. The solution here depends on jQuery. The key solution was in realizing that the visual number of lines is a combination of the number of hard linebreaks and a ratio between the textarea's cols and the length of each hard line.

Here's an application with this in use that hopefully demonstrates the usefulness of this solution.


Comment

 
Name:
Email:
hide my email address.

Your email address will be encoded to prevent email-extraction spiders from reading it so you won't get spammed if you decide to show your email address.