GreenSock: ScrollTrigger Media Queries with matchMedia()
Master responsive animations with GreenSock ScrollTrigger
What You'll Master
Media Query Integration
Learn how to implement CSS-like media queries in JavaScript using ScrollTrigger.matchMedia() for responsive animations.
Cross-Device Optimization
Discover techniques to optimize scroll animations for different screen sizes and device types.
Style Contamination Prevention
Understand how to prevent inline CSS contamination when switching between different media query states.
Transform a single-size scroll animation into a responsive system that adapts seamlessly across desktop and mobile viewports using ScrollTrigger.matchMedia().
Setup Process
Open Project Files
Navigate to Desktop > Class Files > JavaScript Class and open the GSAP-ScrollTrigger-Multiple folder in your code editor.
Preview Current Animation
Open index.html in a browser to see the existing scrolling animation that works well on wide screens.
Test Mobile View
Resize the browser window to simulate mobile size and observe how the animation could be improved for smaller screens.
Current Animation Analysis
Breakpoint Configuration
| Feature | Desktop (600px+) | Mobile (599px-) |
|---|---|---|
| Image Start Position | top 75% | top 75% |
| Image End Position | bottom 70% | 150px 70% |
| Text Animation | bottom 70% | bottom 70% |
| Animation Duration | Full scroll height | Reduced for faster completion |
ScrollTrigger.matchMedia() uses standard CSS media query syntax within JavaScript functions, making it familiar for web developers.
Implementation Steps
Add matchMedia Structure
Initialize ScrollTrigger.matchMedia() with an empty object to contain your responsive animation logic.
Define Breakpoints
Create two functions: one for screens 600px and wider, another for screens 599px and narrower.
Duplicate Animation Code
Move your existing for loop into both media query functions to create separate animation contexts.
Customize Mobile Settings
Modify the start and end values in the mobile function to optimize animation timing for smaller screens.
When resizing windows, GSAP's inline CSS from one media query can contaminate another, causing elements to disappear or behave incorrectly.
ScrollTrigger.saveStyles() Solution
Style Recording
Automatically captures initial inline CSS states for specified elements before animations begin. This creates a clean baseline for media query switches.
Contamination Prevention
Ensures that switching between media queries doesn't leave residual inline styles that interfere with new animations.
Final Implementation Checklist
Specify the exact elements being animated to prevent style contamination
Resize browser window multiple times to ensure smooth transitions
Confirm that both desktop and mobile animations perform optimally
Key Takeaways
