InView Each Element

by Ryan Brackett

HTML

<div style="height: 2000px;">

</div>
<div class="your-div inview">
This
</div>
<div class="your-div-2 inview">
This
</div>

CSS

.your-div {padding: 30px; background: #dedede;}
.your-div-2 {padding: 30px; background: green;}

JavaScript

// ADD CLASSES TO EACH ELEMENT WITH INVIEW CLASS
//// Class while being viewed
//// Class showing has been viewed

$(window).scroll(function() {
  inViewport();
});

$(window).resize(function() {
  inViewport();
});

function inViewport() {
  let targetClass = '.inview',
    height = window.innerHeight,
    elems = document.querySelectorAll(targetClass);


  elems.forEach(function(elem) {

    let rect = elem.getBoundingClientRect();
    let distance_from_bottom_of_viewport = height - rect.top;
    //console.log(distance_from_bottom_of_viewport);
    if (distance_from_bottom_of_viewport > 0) {
      elem.classList.add("inviewport");
      elem.classList.add("viewed");
    } else {
      elem.classList.remove("inviewport");
    }
  });
}