How to create a textarea autorisize with js?

Asked

Viewed 43 times

2

I need to create a text field that grows with what the user writes, but has to be with pure Javascript, without jquery or something like.

1 answer

3

Response taken from:

Stackoverflow English

var observe;
if (window.attachEvent) {
  observe = function(element, event, handler) {
    element.attachEvent('on' + event, handler);
  };
} else {
  observe = function(element, event, handler) {
    element.addEventListener(event, handler, false);
  };
}

function init() {
  var text = document.getElementById('text');

  function resize() {
      text.style.height = 'auto';
      text.style.height = text.scrollHeight + 'px';
    }
    /* 0-timeout to get the already changed text */

  function delayedResize() {
    window.setTimeout(resize, 0);
  }
  observe(text, 'change', resize);
  observe(text, 'cut', delayedResize);
  observe(text, 'paste', delayedResize);
  observe(text, 'drop', delayedResize);
  observe(text, 'keydown', delayedResize);

  text.focus();
  text.select();
  resize();
}
textarea {
  border: 0 none white;
  overflow: hidden;
  padding: 0;
  outline: none;
  background-color: #D0D0D0;
  width: 400px;
}
<body onload="init();">
  <textarea rows="1" style="height: 1em;" id="text"></textarea>
</body>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.