Jc Balantakbo
Jc Balantakbo

Reputation: 115

How to style textarea's height on page load based on it's content?

I have this code, getting data (@note.Description) from the database add adding the data on textareas

@foreach (Models.Note note in Model.listNote)
            {
                <li class="sortable list-group-item noteLI @(note.Positive?"list-group-item-success":"list-group-item-danger") @(note.Pinned?BLL.Constants.DisableProperty:String.Empty)">
                    <input type="checkbox" class="completed">
                    <span class="text"><textarea id="@note.NoteId" sort="@note.Sort" class="notes autoExpand w-100" type="text" style="overflow:hidden">@note.Description</textarea></span>
                    <span class="tools">
                        <i class="pinNote fa fa-thumb-tack"></i>
                        <i class="deleteNote fa fa-trash-o"></i>
                    </span>
                </li>
            }

Some of the data on the database to be placed on the textarea contains more line breaks than others.

Problem: How do you have varying textarea height depending on the content of the textarea on page load?

Checked stackoverflow for solutions and most of them adjust textarea onkeypress which is not what I am looking for.

What I want it to looklike on page load

![enter image description here

Upvotes: 0

Views: 56

Answers (1)

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4557

You can use the scrollHeight property to determine what size you would like to set the <textarea/> to.

window.onload = () => {
  let textarea = document.querySelector('textarea');
  textarea.style.height = `${textarea.scrollHeight}px`;
}
<textarea id='ta'>
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. 
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. 
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. 
</textarea>

Upvotes: 1

Related Questions