5

Can a textarea adapt it's height while inserting text?

I want to hide the textarea's borders, so that users feel they'r typing in an unlimited space.

(The textarea's height should be increased by height of one line when a new line starts)

One way I guessed, is to; copy all texts into a div with same width on each keystroke, then measure the height of the div, then set the div's height for textarea.

One problem I noticed, is scroll bars width that should be subtracted from main width, and on different devices we have 0 to 16px variable scroll bar width..., any suggestions?

Positivity
  • 5,406
  • 6
  • 41
  • 61

2 Answers2

0

Here is What you want First: html here is the text area with id : ta

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <textarea rows="10" cols="10" id="ta">
    </textarea>

And here is the jquery code which works as follows: which increases the height (the rows number) of the text area each time you get into the last line

  $('#ta').keypress( function(){
                    var rows=$('#ta').attr('rows');
                    var text=$('#ta').val();
                    var lines=text.split('\n');
                    if(lines.length==rows){
                        rows++;
                        $('#ta').attr('rows',rows);
                    }
                });

And this css just for hide the border of the textarea so the user feels that he/she writes in the page

#ta{
      border: 0;
      }
-1

You can easily achieve what you're trying to do using elastic.js, it's a simple one-line solution.

$('#note').elastic();
textarea#note {
 width:100%;
 display:block;
 resize: none;
 border: none;
}
textarea:focus {
 outline: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://jquery-elastic.googlecode.com/svn-history/r37/trunk/jquery.elastic.js"></script>
<textarea id="note">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.</textarea>
Fahad Hasan
  • 10,231
  • 4
  • 29
  • 36