Search code examples
javascriptnode.jsvue.jsintersection-observer

Intersection observer calling function at wrong time


when i run the page the intersection observer works just like i want but when i reload the page it teleports me back up to the page(ok thats normal) but then when the viewport is event interacting with the target it calls the function immidiatley. Btw im using vuejs in the project if this has anything to with it

let options = {
  root: null,
  rootMargin: "-20px",
  threshold: 0.375,
};
const widths = ["w-1/3", "w-4/5", "w-1/2", "w-1/2", "w-1/2", "w-2/4", "w-1/2"];
function callback(entries) {
  entries.forEach((entry) => {
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.boundingClientRect
    //   entry.intersectionRatio
    //   entry.intersectionRect
    //   entry.isIntersecting
    //   entry.rootBounds
    //   entry.target
    //   entry.time
  });
  console.log(entries);
  const entry = entries[0];
  if (entry.isIntersecting === true) {
    document.querySelectorAll(".bar-inner").forEach((el, i) => {
      widths.forEach((w, j) => {
        if (i === j) {
          el.classList.remove("w-0");
          el.classList.add(w);
        }
      });
    });
  }
}

let observer = new IntersectionObserver(callback, options);
const tg = document.getElementById("section2");
observer.observe(tg);


Solution

  • It seems that when you reload the page, the page is scrolling from where it was to the top. Thus, observer is getting triggered. This may be happening due to PWA service workers. You need to handle this case separately. For inspiration, you can look at - Refresh Page and Keep Scroll Position