I am suffering from the problem of the scroll position when DOM is added to the top of the parent DOM. The scroll position is automatically set to the top when the scroll position is at the top(targetDOM.scrollTop == 0).
This problem does not occur if the scroll position is 1 or more(targetDOM.scrollTop > 0).
I want to prevent the scroll position from becoming the top automatically if the scroll position is top.
Is there a solution?
example add DOM
var i = 1;
function addDom(){
var content = document.getElementById('content');
for (j = i; j <= i + 9; j++) {
var dom = document.createElement('div');
dom.innerHTML= j;
content.appendChild(dom);
content.insertBefore(dom, content.firstChild);
}
i = j;
}
codepen
You should save current scroll position and scroll size. Then add elements. Get new scroll size and set scroll position to old position plus (new scroll size minus old scroll size):
var i = 1;
function addDom(){
var content = document.getElementById('content');
var curScrollPos = content.scrollTop;
var oldScroll = content.scrollHeight - content.clientHeight;
for (j = i; j <= i + 9; j++) {
var dom = document.createElement('div');
dom.innerHTML= j;
content.appendChild(dom);
content.insertBefore(dom, content.firstChild);
}
var newScroll = content.scrollHeight - content.clientHeight;
content.scrollTop = curScrollPos + (newScroll - oldScroll);
i = j;
}
Tested on Chrome and FF
codepen
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With