[JavaScript] IntersectionObserver API 활용 이벤트 처리

2023. 7. 17. 19:02Tip

728x90
출처:아직도 이 API 모르셨다고요? 개발자 인생 꿀템 소개!  (https://www.youtube.com/watch?v=iZhq7I42uaI)

각 요소의 화면 표시 여부에 따른 동적 애니메이션

 

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <style>
    div {
      height: 200px;
      width: 200px;
      border-radius: 10%;
      background-color: bisque;
      border: 2.5px solid tomato;
      transition: all 0.5s ease-in-out;
      transform: scale(1.5);
      opacity: 0;
      margin: 10px auto 10px auto;
    }

    .visible {
      transform: scale(1);
      opacity: 1;
    }
  </style>

</head>

<body>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</body>

<script>
  document.body.onload = function () {
    const squares = document.querySelectorAll("div")
    const observer = new IntersectionObserver(
      squares =>
        squares.forEach(square => {
          if (square.isIntersecting) square.target.classList.add("visible")
          else square.target.classList.remove("visible")
        }),
      { threshold: 0.3 }
    )
    squares.forEach((square) => observer.observe(square))
  }

</script>
</html>
728x90