javascripthtmlcssparceljs

Scroll to bottom when new message added


I am making a chatbot. I want to scroll to the bottom of the chat box when a new input is given by the user or the Data is sent through API.

It doesn't scroll and scroll just stays in the same position but the data is being added in the chat box

I Have tried the code from other chat bot but it didn't work either

var outputArea = $('#chat-output');
$('#user-input-form').on('submit', function (e) {
  e.preventDefault();

  var message = $('#user-input').val();

  outputArea.append(`
    <div class='bot-message'>
      <div class='message'>
        ${message}
      </div>
    </div>
  `);



  const req = https.request(options, (res) => {
    res.setEncoding('utf8');
    res.on('data', (d) => {
      const myobj = JSON.parse(d);
      if ('narrative' in myobj.conversationalResponse.responses[0]) {
        const temp = myobj.conversationalResponse.responses[0].narrative.text;
        outputArea.append(`
      <div class='user-message'>
        <div class='message'>
          ${temp}
        </div>
      </div>
    `);
      } else if ('imageUrl' in myobj.conversationalResponse.responses[0]) {
        const img = myobj.conversationalResponse.responses[0].imageUrl;
        if ('narrative' in myobj.conversationalResponse.responses[1]) {
          const text_r = myobj.conversationalResponse.responses[1].narrative.text;
          outputArea.append(`
      <div class='user-message'>
      <div class ="message">
      ${text_r}
      <a href=""></a>
      </div>
      </div>
    `);
        } else {
          outputArea.append(`
      <div class='user-message'>
        <div class='message'>
         <img src="" width="300" height="200">
        </div>
      </div>
    `);
        }
      }
    });
  });

  req.on('error', (error) => {
    console.error(error);
  });

  req.write(data);
  req.end();

  $('#user-input').val('');
.form-container {
  width: 400px;
  height: 450px;
  padding: 10px;
  background-color: white;
  overflow: scroll;
  position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chat-popup" id="myForm">
<div class="form-container">

  <div class="chat-output" id="chat-output">
    <div class="user-message">
      <div class="message">Hi! I'm Bot, what's up?</div>
    </div>
  </div>
  <div class="chat-input">
    <form action="#0" id="user-input-form" autocomplete="off">
      <input type="text" id="user-input" class="user-input" placeholder="Talk to the bot.">
    </form>
  </div>
  </br></br>
  <button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</div>
</div>


Solution

  • This worked for me:

    outputArea[0].scrollTop = 9e9;