views:

3756

answers:

4

I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.

So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):

$("#thediv").scrollTop = $("#thediv").scrollHeight;

However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.

The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.

Any ideas guys? This one's got me stumped. Thanks!

+11  A: 

scrollHeight should be the total height of content. scrollTop specifies the pixel offset into that content to be displayed at the top of the element's client area.

So you really want (still using jQuery):

$("#thediv").each( function() 
{
   // certain browsers have a bug such that scrollHeight is too small
   // when content does not fill the client area of the element
   var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);
   this.scrollTop = scrollHeight - this.clientHeight;
});

...which will set the scroll offset to the last clientHeight worth of content.

Shog9
I'm trying to implement your solution to my little problem. Care to help? http://stackoverflow.com/questions/871986/make-chatroom-log-always-scrolled-down
alamodey
This was just what I needed. Thanks! I was trying to get the Jquery scrollTo plugin to work, but this was easier and worked first try.
matt
A: 

Brillaint Shog9, that does the trick perfectly. Thanks!

Bob Somers
A: 

Using a loop to iterate over a jQuery of one element is quite inefficient. When selecting an ID, you can just retrieve the first and unique element of the jQuery using get() or the [] notation.

var div = $("#thediv")[0];

// certain browsers have a bug such that scrollHeight is too small
// when content does not fill the client area of the element
var scrollHeight = Math.max(div.scrollHeight, div.clientHeight);
div.scrollTop = scrollHeight - div.clientHeight;
Vincent Robert
A: 

scrollIntoView

The scrollIntoView method scrolls the element into view.

troelskn