views:

775

answers:

3

I am building a utility page for a web app that I am working on. I have an element that I want to use as a "console" of sorts.

I get entries for the console via Ajax calls (using prototype's Ajax.PeriodicalUpdater).

The problem I'm having is that when I insert new lines to the bottom of the "console", the scrollbar stays in the initial position (so I always see the top lines unless I manually scroll down).

How can I make the scrollbar automatically stay at the bottom?

I am using prototype for a few libraries that require it in this project, so I would prefer to stick with that or regular javascript if possible.

Just as a note, I already tried this:

onComplete: function() { 
    $('console').scrollTop = $('console').scrollHeight;
}

It almost works, except that it is always "one step behind", and I can't see the most recent item.

+3  A: 
new Ajax.PeriodicalUpdater(container, url, {
    onComplete: function() {
        (function() {
            container.scrollTop = container.scrollHeight;
        }).defer();
    }
});
eyelidlessness
Thanks, I actually already tried this method, but it is always one step behind. In other words, I still can't see the most recently added content, until the next thing gets added.
TM
See edit. Does that make a difference?
eyelidlessness
For whatever reason, onComplete doesn't work at all this way. However, this new method works with onSuccess. Thanks!
TM
That's just wacky. I really wish there were more control over timing in browsers.
eyelidlessness
And yeah, function.defer comes in really handy.
eyelidlessness
@eyelidlessness: (pedantry) scrollTop is the distance between the top of the content and the top of the container. scrollHeight is effectively the clientHeight that would be necessary to display the full content. If a browser took your code literally, it would scroll the entire content out of view.
Shog9
@Shog9: Oh, I'm well aware, but no browser does that.
eyelidlessness
+1  A: 

Heh, I was building almost exactly the same thing (an Ajax console) and had issues with my overflowed div not scolling all the way to the bottom.

And Stack Overflow helped me solve it! Hope it helps you too!

http://stackoverflow.com/questions/13362/scrolling-overflowed-divs-with-javascript

EDIT: My question used jQuery, but the problem isn't with the JS framework it's with the CSS attributes you're using. Basically you need get Math.max(div.scrollHeight, div.clientHeight) because some browsers are a bit buggy with those attributes.

Bob Somers
Still had the same problem as before. Could be because I am using prototype instead of jQuery though.
TM
@the edit: Actually, the thing just gets executed too quickly, which is why defer fixed it. The regular css attributes work fine in IE7, FF3, and Chrome, once the defer is added.
TM
A: 

Awesome fix, thanks alot.