Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
NewbieScroll

How to maintain the final state when ScrollTrigger doesn't match the media

Go to solution Solved by GreenSock,

Recommended Posts

Context: I want the counting animation to happen only when the screen size is larger than 1024px 
So for example, starting number is 30 and the number will increment until the target number 50. 

 

However, when I resize the screen the number becomes 30 rather than staying at the target number 50. 

 

From the documentation, it seems like the ScrollTrigger will kill the animation and revert to its original state when the media query doesn't match

However, is there any way to maintain the final state? 

I'm using React and here is the code snippet


I'm new to this forum and GSAP  and thank you in advance for your help and guidance.

Here is the code 

 

import React, { useEffect } from "react"
import { gsap } from "gsap"
import { ScrollTrigger } from "gsap/ScrollTrigger"

const TestPage = () => {
  const stats = [{ finalNum: 50, startNum: 30 }]
  useEffect(() => {
    gsap.registerPlugin(ScrollTrigger)
    ScrollTrigger.matchMedia({
      "(min-width: 1024px)": function () {
        ScrollTrigger.create({
          trigger: "#counter-trigger",
          start: "-=350",
          end: "+=200",
          markers: true,
          animation: gsap.from(".mycounter", {
            duration: 0.55,
            innerText: stats[0].startNum,
            snap: {
              innerText: 1,
            },
            once: true,
          }),
        })
      },
    })
  }, [])

  return (
    <div>
      <div
        style={{
          height: "1000px",
          backgroundColor: "lightcoral",
        }}
      >
        some stuff here
      </div>
      <div my={100} id="counter-trigger">
        <span className="mycounter" style={{ fontSize: "80px" }}>
          {stats[0].finalNum}
        </span>
      </div>
    </div>
  )
}

export default TestPage


 

 

Link to comment
Share on other sites

  • Solution

You can return a cleanup function from your matchMedia function that'll get called when it doesn't match anymore, so just set it to whatever you want in there: 

ScrollTrigger.matchMedia({
  "(min-width: 1024px)": function () {
    ScrollTrigger.create({...});
    return () => {
      document.querySelector("#mycounter").innerText = "50";
    }
  }
});

Does that help?

  • Like 2
Link to comment
Share on other sites

THANK YOU SO MUCH !!!! I didn't know that you can return a cleanup function! 

  • Like 2
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.
×