6
2

More than 1 year has passed since last update.

LocomotiveScroll と ScrollTriggerを連携させる

Posted at

LocomotiveScroll と GSAPのScrollTriggerを連携させたときのメモです。

GSAPの公式がCodepenにサンプルをあげてくれていますので、完成形やより詳細を知りたい方はこちらを参考にしてください。
ポイントとなる部分のコードをみていきます。

gsap.registerPlugin(ScrollTrigger);

const locoScroll = new LocomotiveScroll({
    el: document.querySelector(".smooth-scroll"),
    smooth: true
});
locoScroll.on("scroll", ScrollTrigger.update);

ScrollTrigger.scrollerProxy(".smooth-scroll", {
    scrollTop(value) {
        return arguments.length ? locoScroll.scrollTo(value, 0, 0) : locoScroll.scroll.instance.scroll.y;
    },
    getBoundingClientRect() {
        return {top: 0, left: 0, width: window.innerWidth, height: window.innerHeight};
    },
    pinType: document.querySelector(".smooth-scroll").style.transform ? "transform" : "fixed"
});

ScrollTrigger.addEventListener("refresh", () => locoScroll.update());
ScrollTrigger.refresh();

まずは、GSAPでScrollTriggerを扱えるようにpluginを登録します。

gsap.registerPlugin(ScrollTrigger);

次にLocomotiveScrollの初期化をおこないます。
今回はSmoothScrollの機能を使用したいので smooth: trueを設定します。
elにはSmoothScrollをonにしたい部分を指定します。

const locoScroll = new LocomotiveScroll({
    el: document.querySelector(".smooth-scroll"),
    smooth: true
});

LocomotiveScroll内でscrollイベントが走る度に、ScrollTriggerも更新します。

locoScroll.on("scroll", ScrollTrigger.update);

SmoothScrollがonになるとLocomotiveScrollがスクロールを制御するようになるため、elで指定した部分で色々な高さの調整が行われますので、ScrollTriggerでもそのproxyを使用するようにします。
(この部分はGreenSock公式が公開してくれているcodepenのサンプルにより詳しい解説が書いてくれています...)
LocomotiveScrollを初期化した際のDOM要素と同じものを指定します。

ScrollTrigger.scrollerProxy(".smooth-scroll", {
    scrollTop(value) {
        return arguments.length ? locoScroll.scrollTo(value, 0, 0) : locoScroll.scroll.instance.scroll.y;
    },
    getBoundingClientRect() {
        return {top: 0, left: 0, width: window.innerWidth, height: window.innerHeight};
    },
    pinType: document.querySelector(".smooth-scroll").style.transform ? "transform" : "fixed"
});

そしてwindowが更新される度にScrollTrigger、LocomotiveScrollの両方を更新するようにします。
全ての更新が終わりLocomotiveScrollで高さの調整が終わった後、最後にScrollTriggerをrefreshします。

ScrollTrigger.addEventListener("refresh", () => locoScroll.update());
ScrollTrigger.refresh();
6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2