Auto resizing textarea with Vanilla JavaScript

This is a rewrite of my Auto resizing textarea article to remove the jQuery dependency.

The following function will add the auto resize events to your textareas that have the attribute data-autoresize. It works on mobile devices too.

function addAutoResize() {
  document.querySelectorAll('[data-autoresize]').forEach(function (element) {
    element.style.boxSizing = 'border-box';
    var offset = element.offsetHeight - element.clientHeight;
    document.addEventListener('input', function (event) {
      event.target.style.height = 'auto';
      event.target.style.height = event.target.scrollHeight + offset + 'px';
    });
    element.removeAttribute('data-autoresize');
  });
}
<textarea data-autoresize rows="2"></textarea>

Works best when your textareas have CSS box-sizing: border-box. It also makes sense to remove the browsers resize option:

textarea {
  box-sizing: border-box;
  resize: none;
}

To add the auto resize, just call the function addAutoResize() once your textareas are exposed in DOM. When you load new content via an ajax call, you can savely call addAutoResize() again, it will only apply the events to new textareas.

Demo