2

It is a MERN stack app. I tried to make the height of a textarea responsive to the content using this script.

It looks like the external javascript file is working because I tried putting alert in the for loop and it did work. So I tried putting alert inside the OnInput() function but the alert was not called. Therefore, I think something is wrong with this function.

index.html

<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>

  <script src="/main.js"></script>
</body>

main.js

var tx = document.getElementsByClassName('comment-area-responsive');

for (var i = 0; i < tx.length + 1; i++) {
  //   alert(i);
  tx[i].setAttribute(
    'style',
    'height:' + tx[i].scrollHeight + 'px;overflow-y:hidden;'
  );
  tx[i].addEventListener('change', OnInput, false);
}

function OnInput() {
  this.style.height = 'auto';
  alert('hi2');
  this.style.height = this.scrollHeight + 'px';
}

page

<textarea 
  className='comment-area-responsive' 
  name='title' 
  placeholder='What do you think?' 
  value={text} onChange={e => setText(e.target.value)} 
  required
/>