Search code examples
javascripthtml-tablelazy-loadingvirtual-table

Virtual list render when scroll is set on parent


I have a problem where I want to use virtual list to render a lot of items, before I used to have scroll on virtual list table element and I would use "scrollTop" to find out how much is scrolled and divide that with height of item in a list to find out index of item in array from which I should render it looked like so:

    const scrolledTop = tableElement.scrollTop;
    const pos = Math.floor(scrolledTop / itemHeight);

So "pos" would have index of item from which to render. this calculation would be done whenever user triggered scrollEvent on "tableElement"

Problem is that now I want to have scroll on parent element instead on table, because parent element has some charts and that table, and I want to be able to scroll through those charts instead of them staying on top. But now I can't figure out how can I calculate "pos" from which Index I should render item because now "scollTop" property on table element returns 0 when I scroll.


Solution

  • You can calculate the scroll position relative to the parent element.

    // Assuming 'parentElement' is the element with the scroll
    // and 'itemHeight' is the height of each item in the list
    const parentElement = document.getElementById('parentElement'); // Replace with your parent element's ID
    const itemHeight = 50; // Replace with your actual item height
    
    // Calculate the scroll position of the parent element
    const scrolledTop = parentElement.scrollTop;
    
    // Calculate the index of the item to render
    const pos = Math.floor(scrolledTop / itemHeight);
    
    // Use 'pos' to determine which items to render