<div class="content">
<h1>Intersection Observer Demo</h1>
<p>Scroll down to see elements being observed...</p>
<div class="box" id="box1">Box 1</div>
<div class="box" id="box2">Box 2</div>
<div class="box" id="box3">Box 3</div>
</div>
body,
html {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.content {
width: 80%;
margin: 0 auto 600px auto;
text-align: center;
}
.box {
width: 100%;
height: 300px;
margin-top: 100px;
background-color: lightgray;
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
color: white;
opacity: 0.3;
transition: opacity 0.3s ease;
}
.box.observed {
background-color: steelblue;
opacity: 1;
}
document.addEventListener("DOMContentLoaded", function () {
const boxes = document.querySelectorAll(".box");
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add("observed");
} else {
entry.target.classList.remove("observed");
}
});
},
{ threshold: 0.5 }
);
boxes.forEach((box) => {
observer.observe(box);
});
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.