Home > other >  Why does element prepend removed scroll position?
Why does element prepend removed scroll position?

Time:12-23

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.

CodePudding user response:

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.

CodePudding user response:

Without the full demonstration I would have never understood what you were talking about.

You're moving an child. In other words you first remove it and then you insert it. Once an element is removed, scrollTop makes no sense and is reset.

A solution is to scroll the element down again after it has been inserted:

app.prepend(lastChild);
lastChild.scrollTop = lastChild.scrollHeight;

That seems to work fine.

  • Related