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);
})