1
1

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.

画面内に入ったタイミングで処理をする

Posted at

対象のコンテンツが画面内に入った時にアクションを起こす方法です。

(() => {
  const element = document.getElementById('scroll-action');
  const observer = new IntersectionObserver((entries) => {
    for (const e of entries) {
      if (e.isIntersecting) {
        // 画面内の時の処理
        element.classList.add("-action");
      } else {
        // 画面外の処理
        element.classList.remove("-action");
      }
    }
  });
  observer.observe(element);
})();

上のコードはscroll-actionコンテンツが画面内に入ると-actionクラスを追加、画面外で削除してアニメーションを起こしています。似たものでaddEventListener()メソッドの"scroll"イベントがありますが、あちらはスクロールするたびに処理が走るので、こっちのほうが、パフォーマンスがいいです。

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?