Intersectionobserver example
by hyeyoon
HTML
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css">
<div class="example">
<h1 class="title">Scroll Down <span class="arrow">๐</span></h1>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
CSS
.example {
padding-top: 800px;
padding-bottom: 300px;
width: 100%;
background: #eee;
position: relative;
}
.title {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
}
.arrow {
display: inline-block;
animation: bounce 1s infinite ease;
}
.box {
margin: 0 auto 200px auto;
width: 100px;
height: 100px;
border-radius: 5px;
background: #7de2fc linear-gradient(-225deg, #7de2fc 0%, #b9b6e5 100%);
}
.box.tada {
animation: tada 1s ease;
}
JavaScript
// IntersectionObserver ๋ฅผ ๋ฑ๋กํ๋ค.
const io = new IntersectionObserver(entries => {
entries.forEach(entry => {
// ๊ด์ฐฐ ๋์์ด viewport ์์ ๋ค์ด์จ ๊ฒฝ์ฐ 'tada' ํด๋์ค๋ฅผ ์ถ๊ฐ
if (entry.intersectionRatio > 0) {
entry.target.classList.add('tada');
}
// ๊ทธ ์ธ์ ๊ฒฝ์ฐ 'tada' ํด๋์ค ์ ๊ฑฐ
else {
entry.target.classList.remove('tada');
}
})
})
// ๊ด์ฐฐํ ๋์์ ์ ์ธํ๊ณ , ํด๋น ์์ฑ์ ๊ด์ฐฐ์ํจ๋ค.
const boxElList = document.querySelectorAll('.box');
boxElList.forEach((el) => {
io.observe(el);
})