Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force scrollbar to bottom

I am making a little messaging / chat system that is working nice and fine. The problem is, the <div> which the messages are outputted to does not scroll the way I need it to.

All the new messages are added to the bottom of the div and when more are added and the scrollbar shows up, the scrolling stays at the top of the <div>. I need this to be reversed, so that the scrolling always sticks to the bottom of the <div>.

A good example of what I want would be Steam's chat windows, or even this text input which I am using to fill out the question.

As I would like to avoid jQuery, this has me completely stuck. If you could point me in the correct direction that would be great! I am not sure if HTML and CSS can handle this, or if JavaScript is necessary at all.

like image 530
grep Avatar asked Aug 15 '11 09:08

grep


2 Answers

The Javascript code below should keep your div's scrollbar positioned at the bottom like you described:

var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;

This solution and more information can be found on the link below: http://web.archive.org/web/20080821211053/http://radio.javaranch.com/pascarello/2005/12/14/1134573598403.html

like image 63
michaelx386 Avatar answered Oct 04 '22 17:10

michaelx386


I think this is a better solution:

element.scrollTop = element.scrollHeight - element.clientHeight;
like image 27
Rodan Sotto Avatar answered Oct 04 '22 16:10

Rodan Sotto