1

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?

Best Dev Tutorials
  • 452
  • 2
  • 6
  • 22

2 Answers2

0

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.

Alvaro
  • 40,778
  • 30
  • 164
  • 336
-1

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>
Tigran
  • 2,800
  • 1
  • 19
  • 19