Jorge Costa
Jorge Costa

Reputation: 433

JavaScript check if element is outside top viewport

I have a code that works just fine to check if element is outside of bottom viewport, as follows:

function posY(elm) {
let test = elm, top = 0;

while(!!test && test.tagName.toLowerCase() !== "body") {
    top += test.offsetTop;
    test = test.offsetParent;
}

return top;
}

function viewPortHeight() {
let de = document.documentElement;

if(!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }

return 0;
}

function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}

function checkvisible (elm) {
let vpH = viewPortHeight(), // Viewport Height
    st = scrollY(), // Scroll Top
    y = posY(elm);

return (y > (vpH + st));
}

        if (hasActivity && isHidden) {
            isVisibleCSS = <div className='onscreen'>More activity below ↓</div>;
        } else if (hasActivity && !isHidden) {
            //technically, there's no need for this here, but since I'm paranoid, let's leave it here please.
        }

My question is, how can I adapt this code or create a new one similar to this one that identifies when element is outside of top viewport?

Cheers.

Upvotes: 1

Views: 1685

Answers (1)

Mi-Creativity
Mi-Creativity

Reputation: 9654

For an element to be completely off the view top then the sum of the element's top offset and it's height, like in this JS Fiddle

var $test = document.getElementById('test'),
  $tOffset = $test.offsetTop,
  $tHeight = $test.clientHeight,
  $winH = window.innerHeight,
  $scrollY;


window.addEventListener('scroll', function() {
  $scrollY = window.scrollY;
  if ($scrollY > ($tOffset + $tHeight)) {
    console.log('out of the top');
  }
});
body {
  margin: 0;
  padding: 0;
  padding-top: 200px;
  height: 1500px;
}
#test {
  width: 100px;
  height: 150px;
  background-color: orange;
  margin: 0 auto;
}
<div id="test"></div>

Upvotes: 2

Related Questions