Search code examples
javascriptscroll

Browser scroll, offsets and math


I'm using virtual infinite scroll package from https://github.com/daybrush/infinite-viewer

And I'm trying to manipulate with inner content, so I can scroll any element to viewport programmatically.

For example we have some divs inside: enter image description here

and when clicking on number of the div - it brings into viewport regardless of scroll position, zoom or div position

enter image description here


I don't have even the idea of approach... It is something like:

  • Get divs bounding rect
  • Adjust to parent scroll
  • Adjust to zoom level
  • Calculate target zoom - to fit width (with padding)
  • Calculate X,Y to scroll to
  • Bring the div (go to div)

But no luck yet...

Thanks in advance!


Solution

  • So thanks to Daybrush the solution looks like

    function navigateToPage(pageId) {
      const viewportElement = infiniteViewer.getViewport();
      const pageElement = document.querySelector(`[id="${pageId}"]`);
      const viewportRect = viewportElement.getBoundingClientRect();
      const pageRect = pageElement.getBoundingClientRect();
      const zoom = infiniteViewer.getZoom();
      const offsetLeft = (pageRect.left - viewportRect.left) / zoom;
      const offsetTop = (pageRect.top - viewportRect.top) / zoom;
      const pageWidth = pageRect.width / zoom;
      const pageHeight = pageRect.height / zoom;
      const nextZoom = 2;
    
      infiniteViewer.setTo({
        x: - infiniteViewer.getContainerWidth() / 2 / nextZoom + offsetLeft + pageWidth / 2,
        y: -infiniteViewer.getContainerHeight() / 2 / nextZoom + offsetTop + pageHeight / 2,
        zoom: nextZoom,
        duration: 300,
      });
    }