Ryan
Ryan

Reputation: 1164

TextArea resize automatically based on content

So, I have a <textarea> as part of a form which users will input a list item. I decided to try using some jQuery to extend the height of the <textarea> upon the space was filled. I have got it to work in basic form, but I appear to have an issue, which is that every time the keyup() event is called, the height of the <textarea> increases, instead of when the content is filling it. Here is my code:

HTML:

<textarea class="list_header_itemInput" placeholder="Enter an item..."></textarea>

My CSS:

.list_header_itemInput {
    width: calc(100% - 36px);
    line-height: 18px;
    resize: none;
    max-height: 180px;
}

And finally, my jQuery:

$('.list_header_itemInput').keyup(function() {
    $(this).css({ height: ($(this).height() + 2) });
});

What would I have to change in my code so that I get my intended result?

Upvotes: 1

Views: 174

Answers (2)

MattE_WI
MattE_WI

Reputation: 377

You could set the textarea's height to 1px, then measure the scrollHeight (the number of pixels represented by the scrollbar). Then set your textarea's height to (scrollHeight + 1).

$('.list_header_itemInput').keyup(function() { 
    this.style.height = "1px";
    this.style.height = (this.scrollHeight + 1) + "px";
});

Upvotes: 2

indubitablee
indubitablee

Reputation: 8216

perhaps you can use elastic js?: http://jsfiddle.net/janjarfalk/r3Ekw/ and insert this plugin into your html doc

<script src="http://jquery-elastic.googlecode.com/svn/trunk/jquery.elastic.source.js"></script>

Upvotes: 2

Related Questions