Skip to content

Instantly share code, notes, and snippets.

@BoxPistols
Created August 14, 2021 10:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BoxPistols/282eaebe1d4b88d4c829cb03a5a45f2e to your computer and use it in GitHub Desktop.
Save BoxPistols/282eaebe1d4b88d4c829cb03a5a45f2e to your computer and use it in GitHub Desktop.
Intersection Observer Scroll Animation
<section id="first" class="section">
<div class="section__container">
<p>First section</p>
<p>↓Scroll↓</p>
</div>
</section>
<section id="second" class="section obs">
<div class="section__container">
<p>Second section</p>
</div>
</section>
<section id="third" class="section obs r2l">
<div class="section__container">
<p>Third section</p>
</div>
</section>
<section id="fourth" class="section obs">
<div class="section__container">
<p>Fourth section</p>
</div>
</section>
window.onload = () => {
startObserve();
};
function startObserve() {
// 見えている量が閾値を上回るか下回ったときに呼ばれる
const callback = (entries, observer) => {
entries.forEach((entry) => {
if (entry.intersectionRatio === 1) {
// 100%見えなくなったとき
entry.target.classList.add("active");
} else if (!entry.isIntersecting) {
// 見えている領域が20%を下回ったとき
entry.target.classList.remove("active");
}
});
};
const option = {
// 20%と100%の閾値
threshold: [0.2, 1.0]
};
let observer = new IntersectionObserver(callback, option);
let elements = document.querySelectorAll(".obs");
for (let i = 0; i < elements.length; i++) {
// 同じインスタンスにターゲットとなる要素を渡す
observer.observe(elements[i]);
}
}
// let target = document.querySelector(".obs");
// observer.observe(target);
// }
body {
font-family: YakuHanMP, "Hiragino Mincho ProN", "Noto Serif JP", "Yu Mincho",
YuMincho, serif;
min-height: 500vh;
}
.section {
height: 90vh;
position: relative;
background-color: #ccc;
&__container {
left: 50%;
position: absolute;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
p {
color: white;
font-size: 3rem;
letter-spacing: 1px;
margin: 0;
}
}
#first {
background: dimgray;
}
#second {
background: gray;
}
#third {
background: darkgray;
}
.obs {
p {
opacity: 0;
}
&.active {
p {
//textFadeInR2L
animation-name: textFadeIn;
animation-duration: 1.2s;
animation-fill-mode: forwards;
}
&.r2l {
p {
animation-name: textFadeInR2L;
}
}
}
}
@keyframes textFadeIn {
0% {
opacity: 0;
transform: translateX(-100%);
}
100% {
opacity: 1;
transform: translateX(0%);
}
}
@keyframes textFadeInR2L {
0% {
opacity: 0;
transform: translateX(100%);
}
100% {
opacity: 1;
transform: translateX(0%);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment