4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

かんたん慣性スクロール TweenMax

Last updated at Posted at 2021-09-17

TweenMaxと同ライブラリのScrollPluginを使ってページ全体を慣性スクロールさせる方法のメモです。

おしゃれサイトによくあるマウスホイールを動かすとゆっくり画面のスクロールが終わるやつの簡単な実装です。

import gsap from "gsap";
import { ScrollToPlugin } from "gsap/all";
gsap.registerPlugin(ScrollToPlugin);

function smoothScroll(toBottom) {
  let direction = "-=100";
  if (toBottom) {
    direction = "+=100";
  }
  gsap.to(window, {
    scrollTo: { y: direction, autoKill: true },
    duration: 1,
  });
}

let startY;
function touchstart(e) {
  startY = e.changedTouches[0].pageY;
}
function touchmove(e) {
  e.preventDefault();
  const moveY = e.changedTouches[0].pageY;
  if (moveY < startY) {
    smoothScroll(true);
  } else {
    smoothScroll(false);
  }
}
function mousemove(e) {
  e.preventDefault();
  if (0 < e.deltaY) {
    smoothScroll(true);
  } else {
    smoothScroll(false);
  }
}
document.addEventListener("touchstart", touchstart, { passive: false });
document.addEventListener("touchmove", touchmove, { passive: false });
document.addEventListener("mousewheel", mousemove, { passive: false });

この記事の内容をさらに改善したものをアップしました。
かんたん慣性スクロール ver.2 GSAP ScrollSmoother.js ぽいのを実現するメモ

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?