Ben Lachman Ben Lachman - 1 year ago 72
CSS Question

Preserving scroll position while inserting div, but only when user has scrolled

I have a container

that is used for displaying log messages. I prepend each message as a separate child
element when it is generated. The parent
is set to
such that after the message elements exceed the height of the parent container, it scrolls. The behavior I'm trying to produce is that messages scroll as normal, except that if the user scrolls down through the "history" of the messages they don't scroll/move out of the visible area of the parent
when new messages are prepended to the top of the message list.

My current attempt looks like this:


<div id='log'>
<div id='log-rows'></div>


log: function(text) {
var messageHTML = "<div><span class='timestamp'>" + (new Date()).toISOString() + "</span> - <span class='message'>" + text + "</span></div>";


var firstLogMessage = $('#log-rows').children().first();

$('#log-rows').children().each( function(index, row) {
row.scrollTop += firstLogMessage.height();



#log-rows {
max-height: 250px;
overflow-y: auto;

Answer Source

Edit your log function. This works for me:

function log(text) {
  var messageHTML = "<div><span class='timestamp'>" + (new Date()).toISOString() + "</span> - <span class='message'>" + text + "</span></div>";


  var scrollTop = $("#log-rows").scrollTop();

  if (scrollTop > 0) {
    var childHeight = $("#log-rows div").outerHeight(true); // get's the new element's full height including margin
    var scrollDelta =  scrollTop + childHeight;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download