Autoresizing Textareas

For one of my side projects I wanted to use a textarea that auto resizes to the length of its content. Besides some jQuery plugins and some pure JavaScript examples that didn’t work properly I couldn’t find anything useful, so I tried to implement my own solution.

var resizingTextareas = [].slice.call(document.querySelectorAll('textarea[autoresize]'));

resizingTextareas.forEach(function(textarea) {
  textarea.addEventListener('input', autoresize, false);
});

function autoresize() {
  this.style.height = 'auto';
  this.style.height = this.scrollHeight+'px';
  this.scrollTop = this.scrollHeight;
  window.scrollTo(window.scrollLeft,(this.scrollTop + this.scrollHeight));
}

At first the code finds all textareas with an autoresize attribute. Then it adds a listener for the input event, which calls the autoresize function. The autorize function sets the textarea’s height to auto and immediately changes its height again to its scrollHeight. This has to be done otherwise the scrollHeight isn’t correcly calculated. The line after ensures that the texarea is scrolled to the bottom whenever a new line is added. The last line scrolls the page if the textbox starts to be higher than the viewport.

textarea[autoresize] {
  display: block;
  overflow: hidden;
  resize: none;
}

Setting the display to block prevents a small position change in Chrome, Safari and Opera when the autoresize function is called for the first time. overflow: hidden prevents the scrollbars from showing up and resize: none removes the small handle at the bottom right corner of the textarea.

You may now use autoresizing textareas like so:

<textarea autoresize>Type here and I’ll resize.</textarea>

View the live example on JSBin.

Share on twitter