greensock / GSAP

GSAP (GreenSock Animation Platform), a JavaScript animation library for the modern web

Home Page:https://gsap.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to prevent this GSAP animation from breaking my absolute positioning?

henriquedevelops opened this issue · comments

My objective is to make an image rotate in the same orientation as the user's scroll wheel.

And I managed to do it, but it breaks the positioning (sometimes).

Sometimes when I load the page everything works fine: the image is correctly centered both horizontally and vertically. But sometimes when I load the page the image is centered only horizontally and not vertically.

Here's an example:

Centered

Not centered

I think this is happening because the parent element of the image is the "main" element and it is also displayed with an animation (so the image is animated 2 times, I guess). But I still don't know how to fix it.

CSS:

.wavySectionContainer {
  height: 800px;
  width: vw;
  background-color: var(--primary);
  position: relative;
}

.aboutMe,
.sun {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

HTML:

  <div class="wavySectionContainer">
    <img class="sun"  src="public/sun.png" alt="Wave">
    <p class="aboutMe">Lorem ipsum dolor sit amet consectetur adipisicing elit. Eligendi officia, mollitia cupiditate quae quos voluptatem dolorum? <br><br>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
  </div>

Javascript:

gsap
  .timeline()
  .from(["main", "footer"], { y: "10%", autoAlpha: 0 })
  .to(".sun", {
    scrollTrigger: {
      trigger: ".wavySectionContainer",
      scrub: true,
    },
    rotation: 360,
    duration: 2,
    ease: "none",
  });

Fixed it!

I just had to use a separate timeline for the rotation animation and wrap it in a setTimeout function so that it only starts once the main timeline finishes.

This question has been replied to in the forums:
https://greensock.com/forums/topic/37309-how-to-prevent-this-gsap-animation-from-breaking-my-absolute-positioning/

One mistake for sure is nesting a ScrollTrigger - you cannot logically have a parent timeline control the playhead AND the scroll position (those could be going in completely different directions simultaneously). So you should just apply the ScrollTrigger directly to the timeline animation itself (not the sub-tween).

If you need more help, please make sure you provide a minimal demo. I used your code from above, dropped it into a CodePen, applied the ScrollTrigger to the timeline, and it is missing various elements and doesn't illustrate the problem:
https://codepen.io/GreenSock/pen/jOQWXop?editors=0010

You definitely shouldn't have to use setTimeout(). If you want to wait for another animation to finish, you could either use an onComplete on that, or just sequencing things in a timeline.

Glad you got it working!