Automatically scroll down chat div

Let’s review a few useful concepts about scrolling first:

When should you scroll?

  • User has loaded messages for the first time.
  • New messages have arrived and you are at the bottom of the scroll (you don’t want to force scroll when the user is scrolling up to read previous messages).

Programmatically that is:

if (firstTime) {
  container.scrollTop = container.scrollHeight;
  firstTime = false;
} else if (container.scrollTop + container.clientHeight === container.scrollHeight) {
  container.scrollTop = container.scrollHeight;

Full chat simulator (with JavaScript):

const messages = document.getElementById('messages');

function appendMessage() {
	const message = document.getElementsByClassName('message')[0];
  const newMessage = message.cloneNode(true);

function getMessages() {
	// Prior to getting your messages.
  shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;
   * Get your messages, we'll just simulate it by appending a new one syncronously.
  // After getting your messages.
  if (!shouldScroll) {

function scrollToBottom() {
  messages.scrollTop = messages.scrollHeight;


setInterval(getMessages, 100);
#messages {
  height: 200px;
  overflow-y: auto;
<div id="messages">
  <div class="message">
    Hello world

Leave a Comment