How can I automatically scroll as content is added to the div?

I have a div of fixed sizes in which some JavaScript functions will place text over time. When the amount of text exceeds the height of the window, a scroll bar appears due to overflow: scroll.

The new problem is that the view in the div remains in the same place where more content appears. I want to say that it remains scrolled wherever it is, since more content is shown below, hidden unless you manually scroll down. I want it to automatically scroll to the bottom when new content appears, so that the user naturally sees what has appeared recently, and not the oldest.

Ideas?

+5
source share
2 answers

You can use scrollTopafter each addition of text:

$("div").scrollTop($("div").children().height());

Use the indoor unit to get true height.

DEMO: http://jsfiddle.net/eyY5k/1/

+6
source

I found that this approach works for my needs:

var realHeight = $("#history")[0].scrollHeight;
$("#history").scrollTop(realHeight);

Note that this uses jquery.

0
source

All Articles