0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

IntersectionObserverとwindow.matchMediaを使用して特定幅でのみ要素を監視する

0
Posted at

背景

よく使用する処理なので備忘録として記録

具体的な内容

// ここで監視対象要素を取得しておく
const hogehoge = document.getElementById('hogehoge');

// 交差判定の設定をまとめる
const options = {
    root: null,
    // 交差の基準とする要素の座標値を計算し、下記に反映していく(別途記述が必要)
    rootMargin: '0px 0px -100px 0px',
    threshold: 0
}
// rootMarginが上記の場合、ビューポートに対して最下部から上に向かって100px分は監視範囲が狭まっている状態となる

// 特定の横幅でのみ処理したい内容をまとめる
const callback = (entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        // 交差した場合の処理
      } else {
        // 交差エリアから外れた場合の処理
      }
    });
};

let observer = new IntersectionObserver(callback, options);

// 監視対象要素を登録(特定の横幅に応じて監視開始と監視終了処理をまとめておく)
const startObserve = () => {
    observer.observe(hogehoge);
    console.log('start observe');
}
const stopObserve = () => {
    observer.unobserve(hogehoge);
    console.log('stop observe');
}

// 仮に1000px以下か、それより広い幅かで定義
const mql = window.matchMedia('(max-width:1000px)');

function mqlFuncA(e) {
    if (e.matches) {
      // 希望するmediaQueryの範囲内だった場合に呼び出す処理
      // ここで監視をスタート
      startObserve();
    } else {
      // 希望するmediaQueryの範囲外にだった場合に呼び出す処理
      // ここで監視を解除
      stopObserve();
    }
}

// 範囲内外問わず、ページ読み込み時に実施される処理
mqlFuncA(mql);

// changeイベント発生時に呼び出される処理
mql.addEventListener('change', mqlFuncA);
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?