Tom Bom
Tom Bom

Reputation: 1721

How to render textarea in correct size and auto expand while typing?

I have a textarea and I would like it to load in the size of the value that is already there, and also to automatically expand as I continue typing.

I found these two pieces of JavaScript code work well separately, but when I put them together, one of them stops working. How do I bind them together?

    $("textarea").height( $("textarea")[0].scrollHeight );
    
$(document)
      .one("focus.autoExpand", "textarea.autoExpand", function() {
        var savedValue = this.value;
        this.value = "";
        this.baseScrollHeight = this.scrollHeight;
        this.value = savedValue;
      })
      .on("input.autoExpand", "textarea.autoExpand", function() {
        var minRows = this.getAttribute("data-min-rows") | 0,
          rows;
        this.rows = minRows;
        rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 10);
        this.rows = minRows + rows;
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea name="textarea" class="autoExpand" rows='1' data-min-rows='1'>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</textarea>

Upvotes: 0

Views: 183

Answers (2)

Liam
Liam

Reputation: 6743

You can use this simple jQuery codes to accomplish that.

$('#textarea').on('change keyup keydown paste cut', 'textarea', function () {
        $(this).height(0).height(this.scrollHeight);
    }).find('textarea').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='textarea'>
<textarea name="textarea" class="autoExpand" rows='1' data-min-rows='1'>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</textarea></div>

Upvotes: 1

Racil Hilan
Racil Hilan

Reputation: 25351

As you can see, a JavaScript solution can complex. You can simply use a <span> which adjusts its size automatically as you described, and make it editable by adding the contenteditable="true" property:

div {
  width: 200px;
}

span {
  border: 1px solid #999;
  padding: 3px;
  font-family: Arial;
}
<div>
  <span contenteditable="true">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
</div>

However, if you want to submit the value as part of the form, you'll have to do so by yourself in JavaScript, but that's relatively easy. You can add a hidden field, and assign the value of the span to the hidden field in the onsubmit event of the form. The hidden field will be then submitted with the form.

Upvotes: 0

Related Questions