Jump to content
Search Community

How do I calculate new div height and apply to gsap pin function when screensize changes

NiklasG test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

Hello everyone!

I am new to gsap and its scrolltrigger plugin and now I have my first problem.

  • I have 2 div elements next to each other.
  • When you scroll down, the left one gets pinned until it reaches the bottom of the right one.
  • I calculate the travel distance of the left div with let travelDistance = rightDivHeight-leftDivHeight;

The problem: When the screen gets resized (phone/tablet tilt) the calculation is outdated because the height changes. That throws off the animation. Explained width pictures (see below)

 

How can I write a function that updates every time the screen size changes? I already tried putting the code in a function and call it with window.addEventListener('resize', updateRightDivHeight); But this didn't update the animation :( Do I have to work on the gsap part? Thank you for helping!

gsapProblem.png

See the Pen ExOOxmW by NiklasG (@NiklasG) on CodePen

Link to comment
Share on other sites

  • Solution

Hi @NiklasG and welcome to the GreenSock forums!

 

There shouldn't be any need for all of that. ScrollTrigger runs all it's calculations and setting start and end points on ever refresh, also in this cases is better to use an endTrigger element rather than ran all those calculations.

 

Basically the issue here is that you are calculating that value just one time so when the screen size changes that value remains the same. One alternative is to use a function based value:

const getTravelDistance = () => {
  let rightDivHeight = document.getElementById("right").clientHeight;
  let leftDivHeight = document.getElementById("left").clientHeight;
  return rightDivHeight - leftDivHeight;
};

gsap.to("#left", {
  scrollTrigger: {
    trigger: "#left",
    start: "top center",
    end: () => `+=${getTravelDistance()}`,
    pin: true,
    markers: true,
    pinSpacing: false
  }
});

Another option, as I mentioned, is to use an endTrigger element:

See the Pen jOQQyQb by GreenSock (@GreenSock) on CodePen

 

Hopefully this helps.

Happy Tweening!

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