25% off ProSNIPC25OFF

Auto-Resize Textareas

Dynamically expands any textarea to fit its content as the user types, eliminating the need to scroll inside the field.

JavaScriptby SnipCraft
js
(function () {
  'use strict';

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

  document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('textarea').forEach(function (ta) {
      ta.style.overflow = 'hidden';
      ta.style.resize   = 'none';
      autoResize(ta);
      ta.addEventListener('input',  function () { autoResize(ta); });
      ta.addEventListener('change', function () { autoResize(ta); });
    });
  });
})();
#auto-resize#forms#javascript#textarea#ux