Jump to content
Search Community

Can I simplify this scroll animation code?

SanderQ test
Moderator Tag

Go to solution Solved by mvaneijgen,

Recommended Posts

Hi, I just started out with GSAP, and I have the feeling I'm over-complicating things.

Basically I just want to reveal all the boxes ones the .container element gets scrolled into view. 


Issue 1: When looking at various examples I get the idea that this can be achieved in a much easier/more performant way, but I wouldn't know how.
Issue 2: When scrolling back up, all the .box elements snap to opacity: 0  right before they leave the view. Is there a way to use a different 'start' so they would only disappear when 100% out of view?

See the Pen PoQVYjB by sander-quirynen (@sander-quirynen) on CodePen

Link to comment
Share on other sites

  • Solution

Hi @SanderQ welcome to the forum!


I've tweaked your logic a bit, there is a lot build in to GSAP that can make your live a lot easier! First off I've crated one ScrollTrigger with a Timeline attached to it. This Timeline animates your boxes in a staggered fashion (see the Stagger docs). Each element will animate `0.1` seconds after the last and they will start `from:` a `random` position, there are a lot more options I recommend playing with the interactive demo on the docs page. 


Next ScrollTrigger has toggleActions (see ScrollTrigger docs) which allows you to specify what the timeline should do at certain points, I've set it now to reverse it animation when you scroll away from it back to the top of the page. 


Also the timeline is tweaked a bit, no need for delays, because the Stagger object takes care of that. I find that you usually can get a way with a `.from` or `.to` Tween, because most of the time your element is already at its end state, so just a `.from` works for that. The second Tween on the timeline starts at the exact same time as the first Tween using the position parameter 


See the Pen qBxgBbo?editors=0010 by mvaneijgen (@mvaneijgen) on CodePen


Hope it helps! 

  • Like 2
  • Thanks 1
Link to comment
Share on other sites

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...