Jump to content
Search Community

My ScrollTrigger Start: Top and End: Bottom seems to be getting out of sync when I stretch the width of the browser back and forth.

Zyrus

Recommended Posts

Posted

Hi! Apologies if I post more often. I am currently at the CreativeCodingClub lesson Change Nav Color on Scroll: Part 2 Responsive

on the part 1 of the lesson Its already responsive on my part because I use tailwind and I am trying to figure out how to make it respond to colors as I stretch the screen. doesn't have much of a luck but I know the logic I just don't know how to execute it. so I finished the Part 2 and followed the code. 

This is made on react so its a bit different from the tutorial made in codepen, (I don't think I can show up the problem in code pen)
please disregard the comments I still tweak things to fix the problem I am having right now but I want to let you know that this code work.

import { useGSAP } from "@gsap/react";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import React, { useRef } from "react";

const navItems: string[] = ["Home", "Works", "Profile", "Downloads", "About"];
const sectionBgColor: string[] = [
  "skyblue",
  "green",
  "salmon",
  "violet",
  "pink",
];

const navColor: string[] = [
  "#bae6fd", // Slightly darker skyblue (Tailwind sky-200)
  "#bbf7d0", // Slightly darker green (Tailwind green-200)
  "#ff9e85", // Slightly darker soft salmon pink
  "#e9d5ff", // Slightly darker violet (Tailwind purple-200)
  "#f472b6", // Medium pink (Tailwind pink-400)
];

gsap.registerPlugin(ScrollTrigger);

export default function ColorNav() {
  const container = useRef<HTMLDivElement | null>(null);

  useGSAP(
    () => {
      if (!container.current) return;
      const fullScreenDiv = container.current.querySelectorAll(".fullscreen");

      //sets the color section of div viewport
      gsap.set(fullScreenDiv, {
        backgroundColor: gsap.utils.wrap(sectionBgColor),
      });

      //get the nav height
      const navElem = container.current.querySelector("nav");
      if (!navElem) return;

      let navHeight: number = navElem.offsetHeight;

      // //refresh when value change
      // // ScrollTrigger.addEventListener("refreshInit", () => {
      // //   navHeight = navElem?.offsetHeight ?? 0;
      // // });

      //on each loop create a dedicated scroll trigger to each section
      navItems.forEach((item, index) => {
        ScrollTrigger.create({
          trigger: fullScreenDiv[index],
          animation: gsap.to(navElem, { backgroundColor: navColor[index] }),
          start: () => `top ${navHeight}`,
          end: () => `bottom ${navHeight}`,
          markers: true,
          toggleActions: "restart none none reverse",
          immediateRender: false,
        });
      });

      ScrollTrigger.addEventListener("refreshInit", () => {
        navHeight = navElem.offsetHeight;
      });

      // ScrollTrigger.refresh();
    },
    { scope: container },
  );
  return (
    <div ref={container}>
      <nav className="nav-wrapper bg-amber-200 flex lg:flex-row flex-col justify-center items-center p-10 gap-20 sticky top-0">
        {navItems.map((item, index) => {
          return (
            <div key={index} className="text-2xl">
              <a
                href={`#${item.toLowerCase()}`}
                onClick={() => {
                  console.log("clicked");
                }}
              >
                {item}
              </a>
            </div>
          );
        })}
      </nav>
      {sectionBgColor.map((item, index) => {
        return (
          <div
            id={navItems[index].toLowerCase()}
            key={index}
            className="fullscreen w-full h-dvh bg-gray-400 text-4xl flex flex-col justify-center items-center uppercase"
          >
            {item} - {navItems[index]}
          </div>
        );
      })}
    </div>
  );
}

The animation goes like this:
-the nav bar turns a light version of color when it scroll through the section of viewport divs. if the div is color orange the nav will turn to color light orange.
-the nav is responsive for narrow width the items in nav transform into flex column while on wider screen it transform to flex row. basically the column has higher height value.
-Each div has scroll trigger in it that has a trigger point according to the height of the nav 
so when it is turned to column (for example it turns height to 500px) then the trigger point of animation is after 500px.

now while playing with it I found a problem, from column to row adjusting the width of my browser I noticed that the start:top and end:bottom of the divs goes out of sync, it is really difficult to explain here please bear with me.

I created the project in NextJS so technically I create components that is similar to the lessons I am learning right now.
so on my project I have this  (this might be irrelevant but I want to share it here regardless..)
the container is a locomotive scroll to be applied for the whole project

    <div ref={container}>
      <PinSpacingDemo />
      <BlankDiv />
      <ParallaxDemo />
      <BlankDiv />
      <MultiSectionScroll />
      <LocomotiveScrollDemo />
      <ScrollIntro />
      <BlankDiv />
      <SectionDemo />
      <BlankDiv />
      <ColorNav />
    </div>


 the problem I noticed was when I change the width of the browser back and forth while I am scrolling in the middle (3rd color div) the start and end of the animation goes above my component , for context with markers I can see the first start-end at the div of the SectionDemo making the nav change color out of sync, I attached a photo.

I am not sure why this happens maybe its because I am stacking it with other components? it works well like on the tutorial when I commented the rest of my components. on this scenario.. is it really not advice to stack up components with scroll trigger or at least components that has creating/chainging the config of scroll trigger dynamically?
because I had a problem with some of my scrollTrigger components when it is stacked up to pages.tsx of NextJS. for example the ScrollIntro is a component that plays a timeline before it create a scroll trigger and unhide the div of below it so when I stack it up with other components, the ScrollIntro will by default be scrollable, had this problem where I can't scroll to the bottom maybe because the created scrollTrigger get a new calculation. I gave up on fixing it maybe it just supposed to work when its on the top of the component.

I apologize for the messy post. tldr; it has a problem on scrolling with other stacked components.

 

820036606_1402479661371016_1002171832808722790_n.png

Posted

Hi,

 

Perhaps these demos can help:

See the Pen abXLvWN by GreenSock (@GreenSock) on CodePen.

 

See the Pen XWQaZdV by GreenSock (@GreenSock) on CodePen.

 

Also be sure to use the useGSAP hook for working in Next/React projects:
https://gsap.com/resources/React

 

Also you can create a minimal demo (emphasis on minimal) using the stackblitz starter templates:
https://stackblitz.com/@gsap-dev/collections/gsap-nextjs-starters

 

Finally is important to know exactly where the code is being executed, keep in mind that the order of operations in React is as follows:

  1. render Parent
  2. render Child A
  3. render Child B
  4. layout Child A
  5. layout Child B
  6. layout Parent
  7. effect Child A
  8. effect Child B
  9. effect Parent

So if the code is on each child component it would be a good idea to call ScrollTrigger.refresh after each ScrollTrigger instance is created or run the whole code in the parent component since is the last effect hook called. Since the useGSAP hook leverages useEffect/useLaoyutEffect internally you are certain that all the components are rendered correctly.
One thing you could try is kind of forget about React/Next and just create a simple HTML/CSS/JS setup with Tailwind and see if you run into the same issue.

 

Hopefully this helps

Happy Tweening!

  • Like 1
Posted

Hi Rodrigo. first thanks for reading my lengthy post. I was really frustrated that I can't figure out how to fix this.  apologies if I am reporting 2 problem at one post I believe it is just causing because of my previous component.

I tried the scroll behaviour fix adding to html to override css elements

html {
  scroll-behavior: auto !important;
}

unfortunately, it didn't fix the problem. 

I have this problematic component (ScrollIntro) where it create a scroll trigger then unhide the content-wrapper after the first timeline is done animating and seems like after commenting out a bunch of components on my project I found this likely to be the culprit of why the rest of my scroll trigger goes out of sync.

I tried to put it on the stackblitz, I had to install Tailwind 4 to properly show the elements. I hope this will run properly on your system.
https://stackblitz.com/edit/stackblitz-starters-tp5ymir1?file=app%2Fpage.tsx

I think this causing the problem (ScrollIntro.tsx)
the circleTl invokes the enableScroll when its complete 
enableScroll function unhide the content-wrapper and create a scroll trigger to the next animation which is messageTl
but If there are other components below ScrollIntro it is already have a scroll area.

On the tutorial from Creative Coding Club. this was done as standalone page so it doesn't have any problem. but since I stack the lessons as sketch component I think this is where the problem occur. I just wonder if there is a workaround with it or just I should just put it on comment and run it as standalone component.

   const circleTl = gsap
        .timeline({
          onComplete: () => {
            enableScroll();
          },
        })

        .to(circle, {
          duration: 2,
          x: offset - 100,
          xPercent: 100,
          ease: "power2.inOut",
        })
        .to(".circle", { duration: 1, scale: 80, ease: "linear", left: 0 })
        .from(
          ".greeting p",
          {
            duration: 1,
            ease: "power1.out",
            stagger: 1,
            opacity: 0,
            x: (index) => {
              if (index % 2 === 0) {
                return 200;
              }
              return -200;
            },
          },
          "<+0.3",
        );

      const setMessageOpacity = gsap.quickSetter(".message-wrapper", "opacity");
      setMessageOpacity(1);

      //message tl
      //greeting p fades out its the first text we see before the scrolling start
      const stagger = 10;
      const opacity = 0;
      const messageTl = gsap
        .timeline({
          paused: true,
        })
        .to(".greeting p", {
          duration: 1,
          ease: "power1.out",
          opacity: 0,
          y: (index) => {
            if (index % 2 === 0) {
              return -200;
            }
            return 200;
          },
        })
        .from(".message-wrapper > *", {
          opacity: opacity,
          scale: 1,
          stagger: stagger,
        })
        .to(
          ".message-wrapper > *:not(:last-child)",
          { opacity: opacity, scale: 2, stagger: stagger },
          stagger,
        );

      if (!container.current) return;
      const contentWrapper =
        container.current.querySelector(".content-wrapper");

      function enableScroll(): void {
        //set overide the visibility hidden of the content wrapper
        // contentWrapper?.classList.remove("invicible");
        // gsap.set(contentWrapper, { autoAlpha: 1 });
        gsap.set(contentWrapper, { display: "block" });

        ScrollTrigger.create({
          trigger: hero,
          animation: messageTl,
          // markers: true,
          pin: true,
          scrub: 1,
          start: "top top",
          end: "+=3000px",
        });
      }
    },
    { scope: container },
  );


 

Posted

Hi Zyrus,

 

Thanks for the StackBlitz and for narrowing it down — your instinct about ScrollIntro is right.

 

Stacking components with ScrollTrigger is fine. The problem is layout changing after other ScrollTriggers have already calculated their start/end.

In enableScroll() you’re doing two things that shift the whole page:

  1. gsap.set(contentWrapper, { display: "block" }) — while that content was display: none it had zero height. Every ScrollTrigger created by components below (ColorNav, etc.) measured positions based on that collapsed layout.
  2. Then you create a pinning ScrollTrigger (end: "+=3000px"), which adds pin-spacing and pushes everything further down.

Those other triggers were created earlier (React effects run when the components mount; your pin is created later in onComplete), so their cached start/end values are stale. Resizing forces a refresh against that messed-up baseline, which is why the markers look like they’ve drifted into other sections.

 

Fix: after you reveal the content and create that ScrollTrigger, refresh:

function enableScroll(): void {
  gsap.set(contentWrapper, { display: "block" });

  ScrollTrigger.create({
    trigger: hero,
    animation: messageTl,
    pin: true,
    scrub: 1,
    start: "top top",
    end: "+=3000px",
  });

  ScrollTrigger.refresh(); // critical
}

 

That should bring the stacked sections back in sync once the intro finishes.

 

A few extras for this pattern:

  • Create ScrollTriggers in document order (top → bottom) when you can. If one has to be deferred like yours, call ScrollTrigger.refresh() right after it exists.
  • If you only need to hide the intro content visually but keep its space in the flow, autoAlpha: 0 (what you had commented out) is gentler than toggling display, because it doesn’t collapse height. Then you mainly need refresh() for the pin-spacing.
  • Stacking CCC lessons as sketches on one Next page is totally fine for learning — just remember that any demo that pins or reveals collapsed content must refresh when that layout settles. Running a lesson as its own page avoids the issue because nothing below depends on those measurements.
  • If Locomotive Scroll is on that outer container, wire it with ScrollTrigger’s scrollerProxy and refresh when Locomotive updates. An unintegrated smooth scroller will also throw start/end off.

So you don’t need to comment ScrollIntro out — add the refresh() and keep an eye on create-order / display: none. If anything still looks wrong after that, a minimal StackBlitz with only ScrollIntro + ColorNav would be perfect for another look.

 

Happy Tweening!

Posted

Hello Jack. I've tried adding ScrollTrigger.refresh() even before I posted here I just didn't put it in the code base after it didn't work on me. 

I even tweak some things like removing the end and changing the .to(not last child) animation of messageTl. then adding the refresh at the bottom of the enableScroll function.

here are some thing that I found, the tailwind css - invisible class cannot seem be overwritten by a gsap set ({display: "block"}) 
so either I set a gsap{autoAlpha: 1} or just remove the class of that specific HTML Element.

since it still consume space (white space) on the page , looks like its not the cause of the other ScrollTrigger out of sync. 
however, I found out that pinning the created ScrollTrigger on enableScroll cause this problem.
 

      function enableScroll(): void {
        ScrollTrigger.create({
          trigger: hero,
          animation: messageTl,
          markers: true,
          pin: true,
          scrub: 1,
          start: "top top",
          // end: "+=3000px",
        });

        ScrollTrigger.refresh()

        gsap.set(contentWrapper, { autoAlpha: 1 });
      }

Maybe I'll just refrain creating a scrollTrigger on onComplete when the components is being sandwhiched  between components. as this example as intended to be non-clickable and supposed to be the first thing we see. what I am just doing is making it work along side with other components. 

 

Posted

Hi Zyrus,

 

Yep — you’ve nailed it. The pin is the real troublemaker here, not the invisible / autoAlpha stuff.

 

ScrollTrigger.refresh() alone often isn’t enough when a pin is created after other ScrollTriggers further down the page already exist. Refresh still runs in creation order (unless you tell it otherwise), so the triggers below can recalculate before your intro pin’s spacing is accounted for. That’s exactly this pattern: React mounts ColorNav (etc.) first → those ScrollTriggers are created → later onComplete creates a pin higher up the page.

 

Two ways to fix that if you want them stacked:

function enableScroll(): void {
  gsap.set(contentWrapper, { autoAlpha: 1 }); // layout first

  ScrollTrigger.create({
    trigger: hero,
    animation: messageTl,
    pin: true,
    scrub: 1,
    start: "top top",
    end: "+=3000",
    refreshPriority: 1, // refresh this pin BEFORE the defaults (0) below
  });

  ScrollTrigger.sort(); // or rely on refreshPriority
  ScrollTrigger.refresh();
}

 

refreshPriority (higher = earlier) or ScrollTrigger.sort() makes sure pin-spacing from the intro is baked into the start/end of everything underneath.

 

That said — your instinct about not sandwiching this lesson is totally reasonable. It’s built as a first-screen, non-clickable intro that owns the page and then unlocks scroll. On a real site you’d almost always put that at the top (or on its own route). For CCC sketches, running it standalone (or only as the first component, with everything below created after enableScroll) is the cleanest approach and saves you from fighting create-order across every demo.

 

So: try sort / refreshPriority if you want the stacked playground; otherwise commenting it out / giving it its own page is a perfectly valid choice for how that lesson is designed.

 

Happy Tweening!

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...