html
<!DOCTYPE html>
<html>
<head>
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<script>
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.backgroundColor = 'green';
} else {
entry.target.style.backgroundColor = 'red';
}
});
});
const boxes = document.querySelectorAll('.box');
boxes.forEach(box => {
observer.observe(box);
});
</script>
</body>
</html>