最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Intersection Observer not cleaning up after observing - Stack Overflow

programmeradmin8浏览0评论

I'm creating this section of a website where images would slide into view when in the viewport. I just learned about intersection observer and tried to implement it, and it works fine.
The only problem now is that I want it to observe only once, such that the elements stay in place even after scrolling past but it's not working
The issue is that outside the toggleSectionImageMobile function, observer is no longer defined, so I can't access it. And I don't want to redefine it again.

  useEffect(() => {
    const toggleSectionImageLg = () => {
     // Code for larger screens
    };

    let observer;
    const toggleSectionImageMobile = () => {
      const callback = (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add("show");
          } else {
            entry.target.classList.remove("show");
          }
        });
      };

      const options = {
        root: null,
        threshold: 0.8,
      };

      observer = new IntersectionObserver(callback, options);
      const targets = document.querySelectorAll(".feature-img-mobile");
      targets.forEach((target) => observer.observe(target));
    };

    if (window.innerWidth > 900) {
      window.addEventListener("scroll", toggleSectionImageLg);
      return () => {
        window.removeEventListener("scroll", toggleSectionImageLg);
      };
    } else {
      toggleSectionImageMobile();
      return () => {
        if (observer) {
          const targets = document.querySelectorAll(".feature-img-mobile");
          targets.forEach((target) => observer.unobserve(target));
        }
      };
    }
  }, []);

I tried declaring the observer variable outside using let, but still nothing.
I've also tried moving the unobserve function into the toggleSectionImageMobile, but still didn't work

发布评论

评论列表(0)

  1. 暂无评论