Jacob Collins
Jacob Collins

Reputation: 303

GSAP ScrollTrigger - Create a Timeline for Every Section

I have a "Projects" page where I'm showcasing project pieces and I want each one to fade in on scroll. I'm trying to implement a timeline for each project with the following HTML and JavaScript:

<!-- Page contains multiple projects that follow this template -->
<div id="project-trigger">
     <div class="project">
          <img class="project-image" src="image1" alt="">
          <div class="description">
               <h3 class="project-text">Lorem Ipsum</h3>
               <p class="project-text">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Fuga impedit numquam modi accusamus.</p>
         </div>
     </div>
</div>
let projectTrigger = document.querySelectorAll('#project-trigger');

projectTrigger.forEach(project => {
    let timeline = gsap.timeline({
        scrollTrigger:{
            trigger:"#project-trigger",
            start:"center bottom",
            ease:"power2.easeOut",
            toggleActions: "play none none reverse",
        }
    })

    timeline.from(".project-image",{
        x:-200,
        opacity:0,
        duration:0.5
    }).from(".project-text",{
        x:200,
        opacity:0,
        duration:0.5,
        stagger:0.2
    }, "-=0.5")
}
)

I want the images to fade in from the left, and the text to fade from the right. At the moment, it's not working - the images fade in halfway then stop, and the text doesn't scroll in at all.

Is it possible to implement what I'm after? And if so, where am I going wrong?

CodePen: https://codepen.io/jacobcollinsdev/pen/jOrpKja?editors=1010

Upvotes: 1

Views: 8743

Answers (1)

Zach Saucier
Zach Saucier

Reputation: 26014

Your HTML is invalid. You can't have multiple elements with the same ID. If you need to do something like that, you should use a class instead.

You're also making one of the most common ScrollTrigger mistakes: using generic selectors when you want to use scoped ones. I write more about how to do this in my article about animating efficiently.

Fixing those errors, you should get something like this:

const projectTriggers = document.querySelectorAll(".project-trigger");

projectTriggers.forEach(addTimeline);

function addTimeline(project, index) {
  const image = project.querySelector(".project-image");
  const text = project.querySelector(".project-text");
  
  const timeline = gsap.timeline({
    scrollTrigger: {
      trigger: project,
      start: "center bottom",
      ease: "power2",
      toggleActions: "play none none reverse"
    }
  })
  .from(image, {
    x: -200,
    opacity: 0,
    duration: 0.5
  })
  .from(text, {
    x: 200,
    opacity: 0,
    duration: 0.5,
    stagger: 0.2
  }, "-=0.5");
}

Demo

To get rid of the flash of unstyled content at the start, see this post.

Upvotes: 3

Related Questions