Textarea com altura automática

script de textarea automatico

by thvinic

HTML

<textarea id="simpleEdit" style="height:98px;overflow-y:hidden;">
  ddsf
  sdf
  dsf
  ds
  fsd
  fds
  fd
  sf
  dsf
  dsf
  dsf
  sdf
  df
  dsf
</textarea>

<br><br>
esse script faz com que o script verifique a altura do textarea, e quebra automaticamente até a ultima linha, normalmente com texto muito grande salvo com localstorage esse problema do Textarea é comum.

JavaScript

window.addEventListener('DOMContentLoaded', (event) => {
    var tx = document.getElementsByTagName('textarea');
    for (var i = 0; i < tx.length; i++) {
        tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
        tx[i].addEventListener("input", OnInput, false);
        // Verifica a altura do texto ao carregar a página
        tx[i].style.height = 'auto';
        tx[i].style.height = (tx[i].scrollHeight) + 'px';
    }

    function OnInput(e) {
        this.style.height = 'auto';
        this.style.width = '100%';
        this.style.height = (this.scrollHeight) + 'px';
    }
});