Search code examples
javascriptjquerygsap

How do I correctly invalidate a timeline on refresh in gsap?


I'm trying to implement a horizontally scrolling section using gsap. On resize however, the timeline gets messed up. It's especially visible on the end of the horizontal section, where the amount of white space gets bigger or the site gets cut off (depending on wether you're making the window wider or thinner). invalidateOnRefresh: true is supposed to fix this and recalculate the timeline values on refresh, but it has no effect in my example. How do I implement it correctly?

gsap.registerPlugin(ScrollTrigger);

const tl = gsap.timeline();

var sectionWidth = $(".section").width();

const ST = ScrollTrigger.create({
  animation: tl,
  trigger: ".container",
  start: 0,
  end: sectionWidth * 4,
  scrub: true,
  invalidateOnRefresh: true,
  pin: true,
});


tl.to(".container", 5, {
    x: -sectionWidth
  })
  .to(".container", 5, {
    x: -sectionWidth * 2
  })
  .to(".container", 5, {
    x: -sectionWidth * 3
  })
  .to(".container", 5, {
    x: -sectionWidth * 4
  });
.section {
  width: 100vw;
  height: 100vh;
  background-color: red;
}

.section:nth-child(2n) {
  background-color: blue;
}

.container {
  width: 500vw;
  display: flex;
}

body {
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.8.0/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.10.1/ScrollTrigger.js"></script>

<div class="container">
  <div class="section"></div>
  <div class="section"></div>
  <div class="section"></div>
  <div class="section"></div>
  <div class="section"></div>
</div>


Solution

  • i have added a simple demo similar to yours here: https://codepen.io/PhanDangKhoa96/pen/qByzezd

    Two points to note:

    • use % unit instead of vw for the width, you can read the explanation here
    • should use a callback function for end: () => sectionWidth * 4

    I also simplify the tl

    tl.to(sections, {xPercent: -100 * (sections.length -1)})