It makes sense to me that IntersectionObserver
is preferred to adding scroll-based event listeners these days. Great.
However, I read here and here that a Proxy
offers a more desirable way to do this and that Object.observe
is perhaps even obsolete.
After reading about Proxy
traps for a while, I still can't get my head around how I would use them in my imaginary use case below - or find any good references for it.
The imaginary use case:
- Generate an arbitrary number of
div
s with random background colours. - Each
div
gets anIntersectionObserver
. - When
isIntersecting == true
for any of thediv
s, thebody
's background colour changes to that of thediv
.
How would I even begin to think about implementing this using proxies?
Fiddle here. It actually creates an attractive - if counterintuitive - effect.
let numberOfDivs = 5;
function createDiv(divNumber) {
// set the div's tag name, class name and a unique ID
let aDiv = document.createElement('div');
aDiv.className = 'my-divs';
aDiv.id = 'div' + divNumber;
// set a random hex bg colour for the div;
// drops a leading zero 1/16 of the time but it's not material to the example
aDiv.style.backgroundColor = '#' + Math.floor(Math.random()*16777215).toString(16);
// append the div to the body
document.body.appendChild(aDiv);
// set IntersectionObserver on the div
let observer = new IntersectionObserver(whatsIn, {threshold: 0.5});
observer.observe(aDiv);
}
// create the divs
for ( let i = 0; i < numberOfDivs; i++ ) {
let newDiv = createDiv(i);
}
// examine the IntersectionObserver output whenever isIntersecting changes
function whatsIn(payload) {
console.log("Is " + payload[0].target.id + " intersecting? " + payload[0].isIntersecting);
// change background color based on most recent isIntersecting == true
document.body.style.backgroundColor =
payload[0].isIntersecting
? payload[0].target.style.backgroundColor
: document.body.style.backgroundColor;
}