This function will add the auto resize functionality to your textareas that have the attribute data-autoresize:
function addAutoResize() { document.querySelectorAll('[data-autoresize]').forEach(function (element) { element.style.boxSizing = 'border-box'; var offset = element.offsetHeight - element.clientHeight; element.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 functionality, just call the function addAutoResize() once your textareas are exposed in DOM. When you load new content via an AJAX request, you can savely call addAutoResize() again, it will only apply the events to new textareas.
document.addEventListener("DOMContentLoaded", function() { addAutoResize(); });