OneBite.Dev - Coding blog in a bite size

Auto expand textarea with Javascript as you type

Here is how you can expand or grow your textarea if the content is already more than current height while typing

Unfortunately, HTML didn’t provide a way to auto grow / auto expand our textarea as we type more that current height.

How to auto expand Javascript textarea

Here is the Javascript code to solve this issue

function autoResize() {
  // Store the current scroll position
  var x = window.scrollX || window.pageXOffset;
  var y = window.scrollY || window.pageYOffset;

  // Reset field height
  textarea.style.height = 'inherit';

  // Get the computed styles for the element
  var computed = window.getComputedStyle(textarea);

  // Calculate the height
  var height = parseInt(computed.getPropertyValue('border-top-width'), 10)
    + parseInt(computed.getPropertyValue('padding-top'), 10)
    + textarea.scrollHeight
    + parseInt(computed.getPropertyValue('padding-bottom'), 10)
    + parseInt(computed.getPropertyValue('border-bottom-width'), 10);

  textarea.style.height = height + 'px';

  // Restore the scroll position
  window.scrollTo(x, y);
};

Code explanation

It’s important to store the current x and y.
And later re scroll with window.scrollTo(x, y) so browser didn’t jump to bottom.

If I try without this method, my browser will jump into bottom, as it want to show the current scroll at the top.

javascript