Scroll isElementInViewport

by hohoya33

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.0/animate.min.css">
<div class="slide slide--intro">
<h1>Scroll Event In View Demo</h1>
<p>특정 요소가 뷰포트 안에 들어왔는지 확인</p>
</div>

<div class="slide">
<div class="box box--spin"><span>Spin</span></div>
</div>

<div class="slide">
<div class="box box--grow"><span>Grow</span></div>
</div>

<div class="slide">
<div class="box box--move-right"><span>Move Right</span></div>
</div>

CSS

body {
  background: #eee;
}


.slide {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}
.slide--intro {
  flex-direction: column;
}
.box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 150px;
  height: 150px;
  color: #fff;
  text-align: center;
  background-color: DeepPink;
  transition: -webkit-transform 1s ease-in;
  transition: transform 1s ease-in;
  transition: transform 1s ease-in, -webkit-transform 1s ease-in;
}
.box--spin.box--visible {
  -webkit-transform: rotate(1080deg);
          transform: rotate(1080deg);
}
.box--grow.box--visible {
  -webkit-transform: scale(1.5);
          transform: scale(1.5);
}
.box--move-right.box--visible {
  -webkit-transform: translateX(50px);
          transform: translateX(50px);
}

JavaScript

function isElementInViewport (el) {
  var rect = el.getBoundingClientRect();
  return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

const addEventToEl = (elList) => {
  document.addEventListener('scroll', () => {
    elList.forEach(el => {
      if (isElementInViewport(el)) {
      el.classList.add('box--visible');
      } else {
        el.classList.remove('box--visible');
      }
    })
  })
}

const boxElList = document.querySelectorAll('.box');
addEventToEl(boxElList);