Last message of chat container to move to the top of the container

I have a chatbot which displays messages in a container. When a user enters a message, I want all messages to move up so that the most recent message that the user enters moves to the very top of the container. I thought scrolltop would work but all that does in scroll to the top of the container.

var el = document.querySelector('div');
el.scrollTop = el.scrollHeight;

setTimeout(function(){
  el.scrollTop = 0;
}, 500);
div{width:200px; height:200px; overflow:auto;}
<div>
<br>Start-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-<br>-End
</div>

So in the example above I want the word ‘End’ to be at the top of the container with white space the length of the container below and the ability to scroll upwards to ‘Start’.

Any help woud be great!

Apart scrolling, you can simple append messages to the container.

Let me add a snippet with div as examples (of course you can use assMessage to insert data without timeout, it’s just to show the behavior)

function addMessage(message) {
    var container = document.getElementById('message-container');
    var newMessage = document.createElement('div');
    newMessage.innerHTML = message;
    container.appendChild(newMessage);
  }

  function onNewMessageReceived(input) {
    var userInput = "New Message"; 
    // message validation or handling...
    addMessage(userInput);
  }
  
  setTimeout(onNewMessageReceived, 1000);  
  setTimeout(onNewMessageReceived, 2000);
<div id="message-container">
  <div>Message</div>
  <div>Answer</div>
</div>

Leave a Comment