I suggest you do so when a new item needs to be added, you check if you are at the top, if so, just add a new item.
If not, you get the existing top / top container of your item, add a new item, increase the height of the item container and then update the top of the scroll.
Here is a simple example of how you can do it by adding both top and bottom (by the way, scroll compensation is not required below).
function addItem (totop) { var msgdiv = document.getElementById('items'); var attop = scrollAtTop(msgdiv); var prevtop = parseInt(msgdiv.scrollHeight - msgdiv.scrollTop); if (totop) { msgdiv.innerHTML = 'Long long content ' + (tempCounter++) + '!<br/>' + msgdiv.innerHTML; if (!attop) { updateScroll(msgdiv, parseInt(msgdiv.scrollHeight) - prevtop); } } else { msgdiv.innerHTML += 'Long long content ' + (tempCounter++) + '!<br/>'; } } var tempCounter = 10; function updateScroll(el, top){ el.scrollTop = top; } function scrollAtTop(el){ return (el.scrollTop == 0); }
html, body { height:100%; margin:0; padding:0; } .items{ display: inline-block; width: 300px; height: 220px; border: 1px solid black; overflow: auto; } button { width: 15%; height: 44px; margin: 20px; vertical-align: top; }
<div class="items" id="items"> Long long content 9!<br/> Long long content 8!<br/> Long long content 7!<br/> Long long content 6!<br/> Long long content 5!<br/> Long long content 4!<br/> Long long content 3!<br/> Long long content 2!<br/> Long long content 1!<br/> </div> <button onclick="addItem(true);">Add 2 top</button><button onclick="addItem(false);">Add 2 bottom</button>
LGSon source share