I have a structure like
<div id="parent">
<div>...</div>
<div>...</div>
<div>...</div>
<div>...</div>
</div>
Where the children of parent are scrollable.
If I take on of the elements from inside parent after scrolling.
const child = parent.children[3];
I have a scroll position
child.scrollTop; // Maybe 269px
And when I add it back
parent.prepend(child);
The child looses its scroll position
child.scrollTop; // 0px
My question here is, why does the scroll position get lost in this case?
Full demonstration of what is happening.
Edit: I understand that the element is removed and being added again. The question was more of why the scrollTop property got reset
>Solution :
Because when you prepend(element) it’s actually first removed from the DOM then reinserted at the new position. While it’s removed from the DOM, it doesn’t have a CSS box anymore, no defined size, no scrolling box. When appended again all the scrolling info is reset.
const elem = document.querySelector("ul");
elem.scrollTop = elem.scrollHeight;
console.log("before", elem.scrollTop);
elem.remove();
console.log("after", elem.scrollTop);
console.log("scrollHeight", elem.scrollHeight);
console.log("height", elem.getBoundingClientRect().height);
ul { max-height: 50px; overflow: scroll }
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
Note that there is an active discussion to maybe add a "move" operation to the DOM APIs, but it’s not quite sure yet what this would look like, nor if it would solve this use case.
If you wish to maintain the scrolling position, you’d have to store it before calling .prepend() and set it back after.