
htmlの中で複数回登場する任意のDOM要素が、インプレッション(画面内表示)された時に、一度だけ処理を実行するプログラムを作りました。
なかなか良い例が見つからなかったので、またいつか使うかもしれないので載せておきます。
// 任意のDOM要素のセレクタ
target_selector = '.aaa';
// 1回だけ実行したらイベントを削除するために必要な変数
bind_fnc = [];
fnc_count = 0;
// イベント内容
var Fnc = function (height, y, fnc_count){
// 画面内に表示されたら
if (window.scrollY + window.innerHeight >= y && window.scrollY <= y + height) {
// 任意の処理を実行
console.log('インプレッション');
// イベントを削除する
window.removeEventListener('scroll', bind_fnc[fnc_count], false);
}
}
// 任意のDOM要素でループ
document.querySelectorAll(target_selector).forEach(function (target) {
rect = target.getBoundingClientRect();
height = target.clientHeight;
y = Math.round(window.scrollY + rect.top);
// removeEventListener出来るようにbind。動的な変数名にするために配列に保存。
bind_fnc.push(Fnc.bind(0, height, y, fnc_count));
window.addEventListener('scroll', bind_fnc[fnc_count], false);
fnc_count++;
});