0

I have found many plugins that allow a textarea to be resized vertically and other plugins that allow an input field to be resized horizontally but I have not found one that allows an input field to be resized vertically like Facebook does for it's comment system

How do I resize an input field vertically when the text reaches the end of the input so that the text may go to the next line just like Facebook does with it's comment system ? And how to resize the text also when the shift and enter keys are pressed just like on Facebook ?

j08691
  • 204,283
  • 31
  • 260
  • 272
Ferdine Faithfull
  • 297
  • 1
  • 4
  • 15

3 Answers3

0

This seems to work fairly well. Using a text area you can specify the number of rows and columns it has, then manipulate those with jQuery.

<!-- Looks identical to a text input -->
<textarea cols="1"></textarea>

Now, each time the key is released, a new row will be added for every 20 characters typed.

$('textarea').keyup(function() {
    var rows = $(this).attr('rows'),
        cols = $(this).attr('cols') || 20, // The number of cols is 20 by default
        length = $(this).val().length;

    // After 20 characters are typed, add a new row to the textarea
    if (length % cols === 0) {
      $(this).attr('rows', ++rows);
    }
});
Alex Cassady
  • 116
  • 7
0

As pointed out here: Multiple lines of input in <input type="text" />

If you read the 3rd answer from the top by Sté. He goes over how one might implement a multi-line input box.

"It is possible to make a text-input multi-line by giving it the word-break: break-word; attribute."

Then in the comments there is a link to a functional fiddle outlining a simple implementation one could use. Jeremy Wadhams Fiddle

CSS:

input {
  width: 50px;
  height: 50px;  
  white-space: pre;
  word-break: break-word; 
}

HTML:

 <input type="text" name="a" id="a" value="bla bla bla bla bla" />

JS:

document.getElementById('a').value = 'Am I \n on a new line?';
Community
  • 1
  • 1
floor
  • 1,519
  • 11
  • 24
-1

When a key is pressed, set the height of the textarea to its scrollHeight, like this:

input.onkeydown = function() {
    input.style.height = input.scrollHeight + "px";
}

The scrollheight is always the height of the contents, so this will make the textarea expand to its contents.

Demo

Update: apparently, webkit calculates the scrollHeightas the height of the containing element plus 4px. You can subtract 4px from the scrollHeighton each calculation (demo), but this won't cause the box to shrink when text is removed.

firefoxuser_1
  • 1,793
  • 13
  • 22
  • That is not working, the height is increasing with every press of a key, even if the text has not begun wrapping. – APAD1 Mar 18 '15 at 21:48