1

When the user writes anything in a textarea, and when pressing the enter button to moving to a new line, there is a character created '\n'.

What about if the user continued to write until he got to the end of the line, and then turn in to a new line automatically without pressing the enter button, in this case how can I to know this ?

The following code Will increase the textarea when press the enter button, and I want to doing the same behavior when automatically turn in to a new line without press the enter button:

var textarea = document.getElementById('text');
textarea.onkeyup = function (eve) {
    if (eve.keyCode == 13) { // 13 = enter key
        textarea.style.height = textarea.offsetHeight + 25 + 'px';
    }
};
#text {width:300px;}
<textarea id="text"></textarea>
Lion King
  • 32,851
  • 25
  • 81
  • 143
  • You can figure out how many characters are in a line then `onchange` event check the number of characters in the textarea then divide by the number of characters in a line to see how many lines there are... – brso05 Apr 15 '15 at 13:55
  • [What if you check for scrollbars?](http://stackoverflow.com/q/3238515/1267304) – DontVoteMeDown Apr 15 '15 at 13:55

2 Answers2

0

There are multiple libraries that can do this for you. E.g.

http://www.jacklmoore.com/autosize/

https://alexdunphy.github.io/flexText/

Edit:

As you didn't want to use the library directly, I checked the code of the jacklmoores autosize.

What it does is basically that it sets the height to auto and then uses the scroll height as the height for the textarea. I also changed your onkeyup to onkeydown as to let it resize when holding a key.

var textarea = document.getElementById('text');
textarea.onkeydown = function (eve) {
    textarea.style.height = 'auto'
    textarea.style.height = textarea.scrollHeight+'px';
}

JSFiddle

frich
  • 145
  • 5
-1

var textarea = document.getElementById('text');
textarea.onkeyup = function (eve) {
    if (eve.keyCode == 13) { // 13 = enter key
        textarea.style.height = textarea.offsetHeight + 25 + 'px';
    }
};
#text {width:300px;}
<textarea id="text"></textarea>