Vertically expanding textarea input boxes

19 September 2007   0 comments   Javascript

Mind That Age!

This blog post is 10 years old! Most likely, its content is outdated. Especially if it's technical.

Powered by Fusion×

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.

Follow @peterbe on Twitter

Comments

Thank you for posting a comment

Your email will never ever be published


Related posts

Previous:
Nasty human error in Zope ZEO setup 14 September 2007
Next:
Ugliest site of the month - The Backyard Comedy Club 21 September 2007
Related by Keyword:
Catching a carriage return in bash 23 October 2006
To br / or not to br/ 23 March 2006
Autosaving textarea with AJAX 16 May 2005
Changing the size of a textarea box 18 August 2004
Related by Text:
Fastest way to download a file from S3 29 March 2017
Comparing REAL values in PostgreSQL 07 February 2007
DifferenceFinder (aka. humanreadablediff.py) 06 July 2006
How to do performance micro benchmarks in Python 24 June 2017
input/textarea switcher with jQuery 11 January 2008