I have a virtual scrolling list built with JS in a Cordova app and I want to save the exact node that was at the top of the viewport after each scroll. The complication with virtual scroll is that using scrollTop
is not reliable because nodes are being removed from the top and bottom of the list, which changes scroll position. Is there a reliable and performant way to do this in Javascript? The use case is this: when the user closes and reopens the app, I want to place the user at the same scroll position and ensure that the element at that position is the element that the user last saw right before closing the app. I'm considering this strategy:
- get the element at the top of the list on each scroll, something like this:
scrollableList.addEventListener('scroll', e => {
const topMostElement = document.elementFromPoint(150, 150); // <-- 150px due to some positioning in the app
});
- saving an identifier for that element so that I can then preload the list on app init such that the element is always rendered in that position
I'd like to know if there are other strategies for dealing with this issue in a JS-based virtual scroller. I've seen tutorials for building a virtual scroller in Javascript but haven't seen one that provides implementation details on how to get around this problem. Thanks in advance!
Update 1
The virtual scroll list has a lot of nodes, can be more than 100, each with its own child nodes. This causes its own set of problems so it's important that (where possible) the solution doesn't require iterating through the list of nodes or performing expensive operations on each node, to avoid blocking the main thread.
You can use IntesectionObserver and save the current element inside the localstorage
example: https://jsfiddle.net/6bu0ynkp/