Automatically scroll down chat div

It's hard to tell without knowing the HTML code, but I'd assume your div doesn't have a height set and/or doesn't allow overflow (e.g. through CSS height: 200px; overflow: auto).

I've made a working sample on jsfiddle: http://jsfiddle.net/hu4zqq4x/

I created some dummy HTML markup inside a div that is a) overflowing and b) has a set height. Scrolling is done through calling the function

function getMessages(letter) {
    var div = $("#messages");
    div.scrollTop(div.prop('scrollHeight'));
}

, in this case once on 'documentReady'.

prop('scrollHeight') will access the value of the property on the first element in the set of matched elements.


after append in JQuery,just add this line

<script>
    $("#messages").animate({ scrollTop: 20000000 }, "slow");
</script>

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

  • scrollHeight: total container size.
  • scrollTop: amount of scroll user has done.
  • clientHeight: amount of container a user sees.

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):

https://jsfiddle.net/apvtL9xa/

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

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

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.
   */
  appendMessage();
  // After getting your messages.
  if (!shouldScroll) {
    scrollToBottom();
  }
}

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

scrollToBottom();

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