ラボ > Javascript関連:イベント関連

対象が表示されたら何かしたい(IntersectionObserver())

作成日:2024-06-09, 更新日:2024-06-09

さんぷる

class afterDisplayUtility {
	constructor(options = {}) {
		const defaults = {
			root: null,
			rootMargin: '10px', // 表示領域外の〇pxから検出。 / 10px: 10pxスクロールしたら検出
			threshold: 0.1, // 対象が何%表示で監視するか? / 0.1: 10%表示で処理開始
		};
		this.options = { ...defaults, ...options };
		this.handleIntersect = this.handleIntersect.bind(this);
		this.obs = new IntersectionObserver(this.handleIntersect, this.prms);
	}

	run_AfterDisplay(elm) { // 表示されたら実行する処理
		console.log('Drawing control panel for', elm.textContent);
	}

	run_observe(elm_many) { // 監視開始
		this.obs.disconnect(); // 再実行を考慮していったん解除
		for (let row_elm of elm_many) {
			this.obs.observe(row_elm);
		};
	}

	add_observe(elm) { // 監視追加
		if ( elm ) {
			return;
		}
		this.obs.observe(elm);
	}

	remove_observe(elm) { // 監視解除
		this.obs.unobserve(elm);
	}

	handleIntersect(entries, observer){
		entries.forEach(entry => {
			if (entry.isIntersecting) {
				this.run_AfterDisplay(entry.target);
				// this.obs.unobserve(entry.target); // 必要に応じてアンオブザーブ
			}
		});
	}
}

util_afterDisplay = new afterDisplayUtility();
util_afterDisplay.run_afterDisplay = function(elm) {
	console.log('Drawing control panel for');
}
util_afterDisplay.run_observe(document.querySelectorAll('.hoge'));

// あとで要素を追加・削除したとき
// util_afterDisplay.add_observe(document.querySelector('#aa'));
// util_afterDisplay.remove_observe(document.querySelector('#aa'));