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 = (elem) => {
   const docTop = document.documentElement.scrollTop;
   const docBottom = docTop + document.documentElement.clientHeight;

   const elemTop = elem.offsetTop;
   const elemBottom = elemTop + elem.clientHeight;

   return (docTop <= elemTop) && (elemBottom <= docBottom);
 };

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

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

Demo