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