Search code examples
javascripthtmlscrollprototypejsscrollbar

Make a scrollable element stay "at the bottom" while adding content


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.


Solution

  • new Ajax.PeriodicalUpdater(container, url, {
        onComplete: function() {
            (function() {
                container.scrollTop = container.scrollHeight;
            }).defer();
        }
    });