Using Intersection Observer to check if an element is fully visible on browser viewport
Asked Answered
S

0

6

After a page loads, I’d like to observe an element (addonCard) using the Intersection Observer API to know if that element is fully visible or not. If the element is invisible or partially visible, I want the element to be scrolled into full visibility. If it’s already fully visible, I want the element to stop being observed. From my understanding, you can check for full visibility by setting the threshold property to 1. However, my implementation below doesn’t work (the element is scrolled regardless of whether it's fully visible or not):

let addonCard = this.querySelector(`[addon-id="${param}"]`);
let observer = new IntersectionObserver(
  (entries, observer) => {
    entries.forEach(entry => {
      if (entry.intersectionRatio != 1) {
        let stickyHeaderHeight = document.querySelector(
          "#page-header > .sticky-container"
        ).offsetHeight;
        let topOfTarget = entry.target.offsetTop - stickyHeaderHeight;
        window.scrollTo({
          top: topOfTarget,
          behavior: "smooth"
        });
      } else {
        observer.unobserve(entry.target);
      }
    });
  }, {
    threshold: 1,
  }
);
observer.observe(addonCard);

Can someone explain why this implementation doesn't work and how I can make it work? Why does entry.intersectionRatio never change from 0?

Expected behavior: addonCard should scroll into full visibility if not fully visible. If it's already fully visible, no scrolling should be done.

Actual behavior: Scrolling occurs regardless of whether addonCard is fully visible or not.

Stallfeed answered 17/11, 2020 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.