javascriptjqueryajaxhtmlscroll

Scrolling Overflowed DIVs with JavaScript


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!


Solution

  • 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.