Intersection Observerで文字だけフェードインを作る方法|スクロールアニメの基本解説

スクロールして要素が見えたタイミングでふわっと表示させる「フェードイン」アニメーションは、ページをおしゃれに見せる定番効果です。Intersection Observer を使うと、CSSとJavaScriptだけで軽量に実装できます。


<!-- フェードインさせたい要素 -->
<div class="fadein">
  <p>このボックスがスクロールでフェードインします。</p>
</div>

<div class="fadein">
  <p>複数要素にも対応できます。</p>
</div>
  

1 実装のポイント

画面内へ要素が入ったかどうかを自動で監視する「Intersection Observer API」を利用し、見えた瞬間にis-show クラスを付与する仕組みです。JavaScript 1回の処理で複数の要素に対応でき、パフォーマンスも優れています。

2 functions.php にコードを追加


//-------------------------------------------
// Intersection Observer でフェードインを作る
//-------------------------------------------

/* フェードインJSをフッターで読み込み */
add_action('wp_footer', function() {
?>
<script>
document.addEventListener('DOMContentLoaded', function() {

  const targets = document.querySelectorAll('.fadein');

  const options = {
    root: null,
    rootMargin: '0px 0px -10% 0px',
    threshold: 0
  };

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('is-show');
        observer.unobserve(entry.target);
      }
    });
  }, options);

  targets.forEach(el => observer.observe(el));
});
</script>
<?php
});
  
補足:
functions.php に貼る場合は、<?php ?> タグを省略してご利用ください。

3 javascript にコードを追加

JS を外部ファイルで管理する場合は、以下を fadein.js として読み込めます。

ファイル名:fadein.js
保存先:wp-content/themes/child-theme/js/fadein.js


document.addEventListener('DOMContentLoaded', function() {

  const targets = document.querySelectorAll('.fadein');

  const options = {
    root: null,
    rootMargin: '0px 0px -10% 0px',
    threshold: 0
  };

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.classList.add('is-show');
        observer.unobserve(entry.target);
      }
    });
  }, options);

  targets.forEach(el => observer.observe(el));
});
  

3.1 ディレクトリ構造

  • child-theme/
    • archive.php
    • category.php
    • functions.php
    • footer.php
    • header.php
    • style.css
    • js/
      • fadein.js

4 汎用CSS

CSSだけでシンプルなフェードインアニメーションを適用できます。


/* -------------------------------------------
 * Intersection Observer でフェードインを作る
 * ----------------------------------------- */

.fadein { opacity:0; transform:translateY(20px); transition:all .8s ease; /* 最初は非表示 */ }
.fadein.is-show { opacity:1; transform:translateY(0); /* スクロールで表示 */ }
  

5 完成イメージ

この文字が下からスクロールでフェードインします。

複数要素にも対応できます。

6 代用プラグイン

フェードインエフェクトをノーコードで実装したい場合は以下が便利です:

  • Animate.css + Wow.js
  • Elementor / ブロックエディタのアニメーション機能
  • AOS.js(スクロールアニメーション用)

7 まとめ

Intersection Observer を使えば、ページに負荷をかけず快適にスクロールアニメーションを実装できます。複数要素も簡単に管理でき、モダンなWeb制作で推奨されている手法です。