PagePiling.js determine if elements are in view

232 Views Asked by At

I'm attempting to animate some text when they come into view. Things work fine but when I introduce pagepiling.js, my function for determining if my elements are in view returns false. Here is the function:

function elementInViewport(el) {
    var top    = el.offsetTop;
    var left   = el.offsetLeft;
    var width  = el.offsetWidth;
    var height = el.offsetHeight;

    while (el.offsetParent) {
        el = el.offsetParent;
        top += el.offsetTop;
        left += el.offsetLeft;
    }

    return (
        top < (window.pageYOffset + window.innerHeight) &&
        left < (window.pageXOffset + window.innerWidth) &&
        (top + height) > window.pageYOffset &&
        (left + width) > window.pageXOffset
    );
}

Any ideas on what could be wrong?

2

There are 2 best solutions below

0
On BEST ANSWER

Please check how to use of the pagePiling.js callbacks for that such as afterLoad and onLeave.

You can also check the available example within the examples folder of the github repo.

0
On

This function should work:

function isInView(el) {
  let bb = el.getBoundingClientRect();
  return bb.top <= window.innerHeight && bb.bottom >= 0
    && bb.left <= window.innerWidth && bb.right >= 0;
}

Here is a demo:

document.onscroll = function() {
  document.querySelector('.status').textContent = isInView(document.querySelector('.element')) ? 'IN' : 'OUT';
}

function isInView(el) {
  let bb = el.getBoundingClientRect();
  return bb.top <= window.innerHeight && bb.bottom >= 0
    && bb.left <= window.innerWidth && bb.right >= 0;
}
.before,
.element,
.after {
  height: 200vh;
  background: wheat;
}
.element {
  background: teal;
}
.status {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 1em;
  background: silver;
}
<div class="before">Before</div>
<div class="element">Element</div>
<div class="after">After</div>
<div class="status">...</div>