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) { = 'border-box';
    var offset = element.offsetHeight - element.clientHeight;
    element.addEventListener('input', function (event) { = 'auto'; = + offset + 'px';
<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.