
スクロール後にイベントを実行させるIntersection Observerを使用して、背景色やテキストカラーを変更させる方法の紹介です。
const target = document.querySelectorAll('.section__bg')
const targetArray = Array.prototype.slice.call(target);
const options = {
root: null,
rootMargin: '0px 0px',
threshold: 0.5
};
const observer = new IntersectionObserver(callback, options)
targetArray.forEach((targets) => {
observer.observe(targets)
});
function callback(active) {
active.forEach(function(entry, i) {
const target = entry.target;
if (entry.isIntersecting && !target.classList.contains('is-active')) {
const delay = i * 100
setTimeout(function(){
target.classList.add('is-active');
},delay);
observer.unobserve(target);
}
});
};
Intersection Observer(交差オブザーバー)は指定した範囲に監視対象の要素が交差したタイミングで実行開始します。
const target = document.querySelectorAll('.section__bg')
監視対象要素はdocument.querySelectorAll('.section__bg')
で指定。ここでは、『.section__bg』というクラスを付与した要素を対象にしています。
const options = {
root: null,
rootMargin: '0px 0px',
threshold: 0.5
};
3つのオプションを指定できます。
- root
- 監視対象が交差する相手を指定。未指定や『null』の値を指定した場合は、ビューポートが対象となります。もし、指定する要素がある場合は
document.querySelectorAll()
で指定。
- rootMargin
- rootの周りにmarginを指定。基準値は0px。『100px 0』を指定すると100px手前から実行開始します。
- threshold
- しきい値。どのくらい交差してから処理を開始するのかを指定します。『0.5』は監視対象の要素が50%交差した段階で実行します。
function callback(active) {
active.forEach(function(entry, i) {
const target = entry.target;
if (entry.isIntersecting && !target.classList.contains('is-active')) {
const delay = i * 100
setTimeout(function(){
target.classList.add('is-active');
},delay);
observer.unobserve(target);
}
});
};
上記で、監視対象と交差した後にdocument.querySelectorAll('.section__bg')
で指定した要素へ『is-active』のclassを付与させています。.section__bg.is-active
でスタイルを変更させています。
<section class="section__bg section01"><p>Section01</p></section>
.section__bg {
transition: 2s;
}
.section__bg.section01 {
color: #111;
background-color: #ddd;
}
.section__bg.section01.is-active {
color: #ddd;
background-color: #111;
}