Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does element prepend removed scroll position?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading