gsapを使ったループしないスライダーのアニメーションのやり方

gsap

gsapを使ったループしないスライダーのアニメーションのやり方を紹介します。

デモ

See the Pen
gsap limited slider
by Sosak (@Sosak2021)
on CodePen.

gsapを使ったループしないスライダーのアニメーションのやり方

const btnNext = document.querySelector('.btn-next');
const btnPrev = document.querySelector('.btn-prev');
const container = document.querySelector('.container');
// Array.from()で配列のメソッドが使えるようになる
const slides = Array.from(document.querySelectorAll('.slide'));
const indexIndication = document.querySelector('.counter span:nth-child(1)');
let index = 0;

たくさんあるのでまずは、扱う要素を変数に格納します。
querySelectorAll()を使うスライダーは、Array.from()を使って配列のメソッドを使えるようにします。

f

unction animNext() {
  const TLNEXT = gsap.timeline();

  TLNEXT
    // indexの番号を動的に変更する
    .set(indexIndication, {
      innerText: index + 1,
    })
    .to(slides[index], { duration: 1, x: 0 });
}

function animPrev() {
  const TLPREV = gsap.timeline();
  TLPREV.set(indexIndication, {
    // currentのindex番号を表示
    innerText: index,
  }).to(slides[index], { duration: 1, x: '-100%' });
}

右上にカウンターがあるので、
次へ進むアニメーションは、indexの数増やし、
前へ戻るアニメーションは、現在のindexを表示させます。そのためにgsapのset()を使うことで、JavaScriptのinnerTextにアクセスできます。
その後、x軸の値を変更します。
0にすると元の位置に戻り、-100%にすると、左側にフレームアウトします。

function rejectSlide() {
  gsap.to(container, {
    keyframes: [
      { duration: 0.08, x: -10 },
      { duration: 0.08, x: 8 },
      { duration: 0.08, x: -8 },
      { duration: 0.08, x: 6 },
      { duration: 0.08, x: -6 },
      { duration: 0.08, x: 3 },
      { duration: 0.08, x: 0 },
    ],
  });
}

最初や最後のスライドに来た場合、もうスライドがないことを示すために、揺れるようなアニメーションを付与しています。

function handleDirection(direction) {
  if (direction === 'next') {
    // 最後のスライドなら
    if (index === slides.length - 1) {
      rejectSlide();
      return;
    }
    // すでにs1の一枚目(slides[0])が表示されているので、indexに1足してからanimNext()を実行する
    index++;
    animNext();
  } else if (direction === 'prev') {
    if (index === 0) {
      rejectSlide();
      return;
    }
    // まずは現在のindexのスライドを動かす必要があるので、アニメーション実行してからindexを変化させる
    animPrev();
    index--;
  }
}

次へ進む関数、前へ戻る関数、リジェクトの関数と複数あるので、それらをまとめて処理する関数を作成します。
引数で次へか前へかを渡すことでコンパクトにできます。
次へ進む場合、すでにs1の一枚目(slides[0])が表示されているので、indexに1足してからanimNext()を実行します。
前へ戻る場合、まずは現在のindexのスライドを動かす必要があるので、アニメーション実行してからindexを変化させます。

btnNext.addEventListener('click', () => {
  handleDirection('next');
});

btnPrev.addEventListener('click', () => {
  handleDirection('prev');
});

最後に、ボタンを押したら上でまとめた関数を実行します。

gsap

Posted by devsakaso