How can I make an element scroll only when it is visible on the page?

25 Views Asked by At

I want to achieve a similar effect here: https://typecode.com/good/

I used intersectionObserver to find when my element 'test' is visible on the page.

Then when it is visible I want that element's background position Y to change as I scroll.

This is what I tried:

 const [scrollPercentage, setScrollPercentage] = useState(0);

  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          // console.log("entry", entry.isIntersecting);
          if (entry.isIntersecting) {
            console.log("You can see me!");
            const handleScroll = () => {
              const scrollTop = window.scrollY;
              setScrollPercentage(
                Math.max(
                  0,
                  Math.min((scrollTop / window.innerHeight) * 100, 100)
                )
              );
            };
            window.addEventListener("scroll", handleScroll);
          } else {
            console.log("You can not see me!");
          }
        });
      },
      {
        threshold: 1, // Start observing when 25% of the element is visible
      }
    );

    const targetElement = document.getElementById("test");
    if (targetElement) {
      observer.observe(targetElement);
    }

    // Cleanup
    return () => {
      observer.disconnect();
    };
    // Cleanup scroll event listener when the component is unmounted
  }, []);

Here's the element I'm observing:

<div
    id="test"
            className="scroll test w-[400px] h-[400px] border border-[red]"
            style={{
              backgroundImage:
                `url(${img.src})`,

              width: "400px",
              backgroundSize: "cover",
              backgroundRepeat: "no-repeat",
              backgroundPosition: `50%  ${scrollPercentage}%`,
            }}
          ></div>

But looks like it scrolls as soon as I scroll. So if the element is further down the page you won't see the content scroll bc it will already be at scrolled to the bottom.

0

There are 0 best solutions below