Jump to content


ScrollTrigger changing background colors/gradients on scroll

Go to solution Solved by mvaneijgen,

Recommended Posts

I have a page with several sections of varying lengths.  As the user scrolls from one section to the next the background should change between an alternating colour scheme of linear-gradients and solid colours. I'm not sure of the best way to approach this, in my attached pen I am looping through each section and using a switch statement to define specific background colours for each section. 


I think there are two specific problems, the first has to deal with the trigger start, it's currently start: top '-=' + (singleDuration * i) where singleDuration  = totalDuration / sections.lengthI can't think of a good way to trigger the animation when the top of the section is at the top of the window because the sections are of variable heights.

The other issue is the actual animation/background color change.  Right now it's working sporadically, this may be fixed once I get the above issue resolved.

See the Pen MWQgBQJ?editors=1010 by tfantina (@tfantina) on CodePen

Link to comment
Share on other sites

  • Solution

I've never worked with a switch statement before, so forgive me for not using it. What you want is to have a trigger at each section right, so the easiest way is to just crate a scrollTrigger for each section. Then you don't need to calculate anything weird and can just use the top and bottom of the section you're working on.


I've just used some random gradients colors, but it shows you it working. I've used a wrap function this loops through an array and it doesn't matter if there are 10 sections, it will just keep looping the the array of the three I've set. 


See the Pen BaYBGOa?editors=1011 by mvaneijgen (@mvaneijgen) on CodePen

  • Like 4
Link to comment
Share on other sites

Awesome, thank you this is much simpler.

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.