0

I have a div which contains a chat box. Whenever a new message arrives, it is appended to the box - and I want to automatically scroll the box to the bottom (to show the new message). How can I accomplish this?

<div  id="chatting" style="overflow: auto; background-color: #fff; border: solid 2px #dedede; width: 600px;  height: 500px; padding: 10px;">
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
  hello<br/>
</div>
Troy Alford
  • 26,660
  • 10
  • 64
  • 82
tarek
  • 17
  • 5

1 Answers1

5

You can accomplish this by setting the scrollTop property of the chat window div. To scroll to the bottom of the div, set scrollTop equal to scrollHeight:

var chatWindow = document.getElementById('chating');
chatWindow.scrollTop = chatWindow.scrollHeight;​

http://jsfiddle.net/Ln8Hd/

Alternatively, using jQuery:

var chatWindow = $("#chating");
chatWindow.scrollTop(chatWindow[0].scrollHeight);

You'll want to call this each time a chat message has been added to the div.

RoccoC5
  • 4,185
  • 16
  • 20