Autofit multiple textarea's height to loaded content

Viewed 190

I wrote a html/php page in order to update database content. The page has several forms (one for each db row I need to edit), and every form has several textarea fields.

I would like to fit every textarea's height to its content (as retrieved from db), using pure JavaScript (no jQuery).

I've found the following JS function:

function autoResize() {
  this.style.height = 'auto';
  this.style.height = this.scrollHeight + 'px';
} 

But how can I use it for every textarea field in the page? Is there a better way to achieve the goal?

Thanks!

UPDATED

Maybe this is a good solution:

var els = document.querySelectorAll('textarea');
Array.from(els).forEach((el) => {
    var offset = el.offsetHeight - el.clientHeight;
    el.style.height = 0;
    el.style.height = el.scrollHeight + offset + 'px';
    el.addEventListener('input', function() {
        el.style.height = el.scrollHeight + offset + 'px';
    });
});

Could it be done in a better way?

1 Answers

Check out this snippet:

<script>
    var content = document.getElementsByClassName('db-content');
    for(var i=0; i<content.length; i++){
        content[i].style.height = 'auto';
        content[i].style.height = content[i].scrollHeight + 'px';
    }
</script>

You have to apply same class to all <textarea> (db-content in the above snippet) and add this script after them. In the script we are looking for all of those <textarea> by their class name and storing them in an array. Next we loop through the array and apply style to all <textarea>.

Related