How to create a textarea autorisize with js? [duplicate]

2

I need to create a text field that grows with what the user types, but it has to be with pure JavaScript, without jquery or anything like that.

    
asked by anonymous 29.12.2016 / 13:32

1 answer

3

Answer 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>
    
29.12.2016 / 13:36