requestAnimationFrame Sample

by rough cheap

HTML

<div class="state">Status</div>
<div class="box">
  <div class="item">
    Box1
  </div>
</div>

<div class="box">
  <div class="item">
    Box1
  </div>
</div>

CSS

.box {
  margin: 800px 0;
  width: 300px;
  height: 300px;
  background-color: cyan;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.item {
  font-size: 1.8rem;
  font-weight: bold;
}

.state {
  position: fixed;
  top: 0;
  right: 0;
}

JavaScript

(function() {
  var requestAnimationFrame =
    window.requestAnimationFrame || window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  var state = document.querySelector('.state');
  var boxes = document.getElementsByClassName('box');
  let clientHeight = document.documentElement.clientHeight;
  let ticking = false;

  window.addEventListener('scroll', scrollFunc);
  window.addEventListener('resize', scrollFunc);

  function scrollFunc(e) {
    if (!ticking) {
      requestAnimationFrame(function() {
        let scrollY = window.scrollY;
        let bottomY = scrollY + clientHeight;
        var mesg = [];
        Array.from(boxes).forEach((target) => {
          let rect = target.getBoundingClientRect();
          let top = scrollY + rect.top;
          let bottom = scrollY + rect.bottom;
          mesg.push((scrollY < top && top < bottomY) || (scrollY < bottom) && (bottom < bottomY) ? 'visible' : 'unvisible');
        });
        state.innerHTML = mesg.join('<br>');
        ticking = false;
      });
    }
    ticking = true;
  }
})();