Resize text box to fit all content

I am trying to resize a text box to fit the content in it as much as possible. Here are my current efforts:

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 pretty well, but doesn't seem to work when the user “clicks” the text on the next line, filling in the width. (Note: the 75 used here is the width of my text box in characters)

There is also an odd effect when [enter] [key] makes textarea 2 lines past the end of the text, then the next [key] returns it to the expected additional line. I tried just setting c to 2 if c <= 1, with no effect. This is not a huge deal, but it would be nice to fix it.

Any help would be appreciated.

Note: this function is called by pressing a key.

+3
1

, , Math.ceiling(), Math.ceil().

...

. - var , , . JSLint, .

. , , . , , cols textarea.

- , a, b, c, .

:

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;
}

SO post Autosizing Textarea, Triptych.

+8

Source: https://habr.com/ru/post/1710383/


All Articles