Auto resizing textarea

If you're after auto resizing textareas in Vanilla JavaScript, check out this article.

This jQuery script will add the auto resize events to your textareas with the attribute data-autoresize:

jQuery.each(jQuery('textarea[data-autoresize]'), function() {
  var offset = this.offsetHeight - this.clientHeight;
 
  var resizeTextarea = function(el) {
    jQuery(el).css('height', 'auto').css('height', el.scrollHeight + offset);
  };
  jQuery(this).on('keyup input', function() { resizeTextarea(this); }).removeAttr('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;
}

I like using this script in a function, so when you create new textareas with JavaScript or when you load new content containing textareas with AJAX, you can just call the function to add the events. The script will only add the events once, so it is save to call anytime.

Demo