<div class="mainBox">
<h3>Intersection Observer Example</h3>
<p>Visible area / view port
</p>
<p>
When target box intersect with this view by 30%, 50% and 80% color of the target box changes to red, blue and green respectively.
</p>
<div class="targetBox"></div>
</div>
.mainBox {
border: 1px solid black;
width: 500px;
height: 400px;
margin: 0 auto;
overflow-y: scroll;
text-align: center;
}
.targetBox {
width: 300px;
height: 100px;
border: 1px solid #ccc;
background: #ccc;
margin: 50px auto;
margin-top: 500px;
color: #fff;
padding: 10px;
}
if(!("IntersectionObserver" in window)) {
document.body.innerText = "Not supported by your browser";
}
window.addEventListener("load", function(event) {
const mainBox = document.querySelector(".mainBox");
/* Creating observer */
const options = {
root: mainBox,
rootMargin: '0px',
threshold: [0.3, 0.5, 0.8, 1]
};
const observer = new IntersectionObserver(handler, options);
/* Defining target object */
const target = document.querySelector(".targetBox");
observer.observe(target);
}, false);
/* Defining callback handler */
function handler(entries, observer) {
console.log("Observer handler called: ");
entries.forEach(entry => {
const intersectionRatio = entry.intersectionRatio.toFixed(2);
entry.target.innerText = "Interserction ratio: " + intersectionRatio;
if (intersectionRatio > 0.8) {
entry.target.style.background = "green";
} else if(intersectionRatio > 0.5) {
entry.target.style.background = "blue";
} else if(intersectionRatio > 0.2) {
entry.target.style.background = "red";
}
});
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.