tags:

views:

455

answers:

2

I'm trying to resize a textarea to fit the content in it, as tightly as possible. Here's my current effort:

function resizeTextarea(t) {
a = t.value.split('\n');
b = 1;
for (x = 0; x < a.length; x++) {
 c = a[x].length;
 if (c >= 75) b += Math.ceiling(c/75);
 }
b += a.length;
t.rows = b;
}

This works fairly well, but seems to fail when the user "pushes" text onto the next line by filling up the width. (Note: the 75 used here is representative of the width of my textarea in characters)

There's also an odd effect where [enter][key] makes the textarea 2 lines past the end of the text, then the next [key] takes it back to the expected one extra line. I've tried just setting c to 2 if c<=1, with no effect. This one isn't a huge deal, but it would be nice to correct.

Any help would be appreciated.

Note: this function is called on key down.

+1  A: 

Your code fails because there is no such method as Math.ceiling(), it's called Math.ceil() instead.

Beside that...

All the variables inside your function are global. This is not a good practice - you should always add var keyword to your variable declarations to make the variable private to that function - otherwise you might accidentally modify some global variable and cause really bad stuff to happen. Use JSLint to check your code for problems like that.

It's also not good to hard-code the width of the text area into your function. This way you can't use your resizing function for other textareas that may have different width. In the current case it's probably best to read the width dynamically from the cols attribute of textarea.

Renaming your variables to something more meaningful than a, b, c would also improve the readability quite a lot.

For example:

function resizeTextarea(textarea) {
  var lines = textarea.value.split('\n');
  var width = textarea.cols;
  var height = 1;
  for (var i = 0; i < lines.length; i++) {
    var linelength = lines[i].length;
    if (linelength >= width) {
      height += Math.ceil(linelength / width);
    }
  }
  height += lines.length;
  textarea.rows = height;
}

I suggest you also study the answers for SO post Autosizing Textarea, pointed out by Triptych.

Rene Saarsoo
I was modifying a function I found online. I had just recently attempted changing from floor to ceiling.
Shadow
A: 

I found a different solution.

Shadow
… care to share?
David Wolever