Creating Sticky Cards on Scroll with GSAP and ScrollTrigger

Article

Creating Sticky Cards on Scroll with GSAP and ScrollTrigger

Hi guys, it's been a while again!
I've been busy due to my side project. :)

I'll show you a codepen with sticky cards that animate as you scroll that you often see in websites.



Key JavaScript Functions for Sticky Animation

To achieve the sticky animation effect, GSAP and ScrollTrigger play a crucial role. Let's dive into each one and understand how they contribute to creating the dynamic scroll-based animation.

const pinnedSections = gsap.utils.toArray(".pinned");


The gsap.utils.toArray() function converts a NodeList of elements (in this case, all elements with the class .pinned) into a proper array. This makes it easier to iterate over these elements and apply animations to each one.

Trigger each section

gsap.to(section, {
  scrollTrigger: {
    trigger: section,
    start: "top top",
    end: index === sections.length ? `+=${lastCard.offsetHeight / 2}` : footer.offsetTop - window.innerHeight,
    pin: true,
    pinSpacing: false,
    scrub: 1,
  },
});


a following line of code is the key point here.
index === sections.length ? +=${lastCard.offsetHeight / 2} : footer.offsetTop - window.innerHeight:

  • index === sections.length: This checks if the current section is the last section in the pinnedSections array.
  • +=${lastCard.offsetHeight / 2}: If the current section is the last one, the end point of the scroll trigger is set to half the height of the lastCard element added to the current scroll position.
  • footer.offsetTop - window.innerHeight: If the current section is not the last one, the end point of the scroll trigger is set to the top offset of the footer element minus the height of the window. This means the scroll trigger will end when the top of the footer reaches the bottom of the viewport.


Header animation with gsap.fromTo()

gsap.fromTo(
  img,
  { scale: 1, opacity: 1 },
  {
    scale: 0.3,
    opacity: 0.01,
    ease: "none",
    scrollTrigger: {
      trigger: section,
      start: "top top",
      end: endScalePoint,
      scrub: 1,
    },
  }
);

It animates the img elements within each pinned section from a scale of 1 and full opacity to a scale of 0.3 and almost transparent.


Conclusion

With this setup, your sticky cards will animate beautifully as the user scrolls through the page, creating an engaging and dynamic experience.
Happy coding!

Matane!

Categories