Categories
interview

Is Element in View

<body onscroll="onscroll()">

  <div style="width: 400px; height:800px; border:1px solid #222;">Scroll Down</div>

  <div id="demo">
    Demo
  </div>

</body>
const isInView = (element) => {
  const {
    top,
    right,
    bottom,
    left
  } = element.getBoundingClientRect();

  return top >= 0 &&
    left >= 0 &&
    right <= (window.innerWidth || document.documentElement.clientWidth) &&
    bottom <= (window.innerHeight || document.documentElemetn.clientHeight);
};

const demo = document.getElementById('demo');

const onscroll = function() {
  console.log(isInView(demo));
};

Demo