How would I achieve this scroll background colour change effect?

Viewed 54

Basically, assume I have 10 sections. Each have a different colour assigned to them for background colour.

When the user scrolls down from sections 1 through 10, I would like the tag background colour to change accordingly, depending which section is on screen.

Assuming the height of the viewport is 1000px, I would like the function to find out which section is currently at 800px out of 1000px, so the bottom 20%, then find the background color of that section in the bottom 20% and apply it to the tag until the user either scrolls to the next section, or scrolls up and another component takes over the background colour.

I have tried to use IntersectionObservor for this but I don't think it is the best approach for what I want.

Currently, my setup is, I am rendering multiple components after each other, each of them has a data attribute of "data-background={background}"

Then, the observer loops through, adds them all to the observer, and watches to find which one is on screen, but it isn't working completely for what I need.

Is there an easier way to achieve what I am looking for?

Here is the code I have so far

import Page from "../components/common/Page";
import Hero from "../components/molecules/Hero";
import TechStack from "@/components/organisms/TechStack";
import { useEffect } from "react";

const Home = () => {
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          console.log("entry", entry);
          if (entry.isIntersecting) {
            document.body.style.backgroundColor =
              entry.target.dataset.background;
          }
        });
      },

      { threshold: [0.20] }
    );
    // create an array of all the components to be watched
    const components = [...document.querySelectorAll("[data-background]")];
    components.forEach((component) => {
      observer.observe(component);
    });
  }, []);

  return (
    <Page seo={{ title: "Starter Kit" }}>
      <Hero />
      <TechStack background="white"/>
      <TechStack background="grey" />
      <TechStack background="blue"/>
      <TechStack background="green"/>
      <TechStack background="grey"/>
      <TechStack background="white"/>
    </Page>
  );
};

export default Home;
1 Answers
Related