It's pretty easy to tell with an intersection observer when the entirety of an element in within the viewport. The code is roughly like so:
// get an element
const thingIWantEntirelyInView = $("#Thing")[0];
const checkInView = new IntersectionObserver((event) => {
console.log("It's in view");
}, {
root: null, // viewport
threshold: 1.0,
});
checkInView.observe(thingIWantEntirelyInView);
What I can't figure out, though, is how to flip it around, so it's less like contain and more like cover. I want to know when my element (which is larger than the viewport) is totally covering the screen.
I tried switching the places of null
and thingIWantEntirelyInView
above, but that didn't work.
I also tried adding a position fixed height: 100vh; width: 100vw
element to the page and checking the intersection with that, but it appears intersection observers don't work with two elements that don't have a parent child relationship? Maybe I did the code wrong, but here's an example:
const thingIWantFillingView = document.getElementById("BigScrolly");
const viewPort = document.getElementById("ViewPort");
// what I tried
const checkInView = new IntersectionObserver((event) => {
console.log("This never seems to happen never happen");
}, {
root: thingIWantFillingView,
threshold: 0.5,
});
// when the viewport is at least half inside BigScrolly
checkInView.observe(viewPort);
// example of the thing I don't want
const checkTouchView = new IntersectionObserver((event) => {
console.log("It has touched the viewport");
}, {
root: null,
threshold: 0,
});
// when BigScrolly has touched the viewport
checkTouchView.observe(thingIWantFillingView);
#ViewPort {
position: fixed;
height: 100vh;
width: 100vw;
top: 0px;
left: 0px;
pointer-events: none;
border: 2px solid red;
box-sizing: border-box;
}
#SomePreviousThing {
height: 100vh;
}
#BigScrolly {
height: 300vh;
background: linear-gradient(#FFEEEA, #222);
}
<div id="ViewPort"></div>
<div id="SomePreviousThing">
Ignore this section, scroll down.
</div>
<div id="BigScrolly"></div>
How can I tell when one of my elements is totally covering the screen using Intersection Observers?