JavaScript
Learn Intersection Observer in 4 Minutes
script.js
// AZUL CODING ---------------------------------------
// JavaScript - Learn Intersection Observer in 4 Minutes
// https://youtu.be/P01XuGslcW8
function setupIntersectionObserver() {
const options = {
root: null,
rootMargin: "0px",
threshold: 0.2 // When 20% of the element is visible
};
const observer = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add("visible");
// Optional: Stop observing the element after it becomes visible
// observer.unobserve(entry.target);
} else {
// Optional: Remove the visible class when element is not in view
// entry.target.classList.remove("visible");
}
});
}, options);
document.querySelectorAll(".image-container").forEach(container => {
observer.observe(container);
});
}
window.addEventListener("load", setupIntersectionObserver);
index.html
<!-- AZUL CODING --------------------------------------- -->
<!-- JavaScript - Learn Intersection Observer in 4 Minutes -->
<!-- https://youtu.be/P01XuGslcW8 -->
<!DOCTYPE html>
<html>
<head>
<title>Azul Coding</title>
<style>
body {
margin: 90px 30px;
background-color: #03506E;
color: white;
max-width: 600px;
}
* {
font-family: 'Inter', system-ui, sans-serif;
font-weight: 500;
font-size: 18px;
}
h1 {
font-size: 36px;
font-weight: 600;
background: #49C8FC;
color: #03506E;
display: inline;
padding: 3px 10px;
box-decoration-break: clone;
}
h1 + p {
margin-left: 10px;
}
#images-container {
margin-top: 90px;
}
.image-container {
margin-bottom: 100px;
opacity: 0;
transform: translateY(20px);
transition: opacity 0.8s ease, transform 0.8s ease;
}
.image-container.visible {
opacity: 1;
transform: translateY(0);
}
img {
max-width: 100%;
height: auto;
display: block;
border-radius: 5px;
aspect-ratio: 16 / 9;
}
.caption {
text-align: center;
margin-top: 10px;
font-style: italic;
}
</style>
<script defer src="script.js"></script>
</head>
<body>
<h1>Intersection Observer</h1>
<p>Scroll down to see images fade in as they enter the viewport.</p>
<div id="images-container">
<div class="image-container">
<img src="/images/image1.jpg" alt="">
<div class="caption">Pembrokeshire</div>
</div>
<div class="image-container">
<img src="/images/image2.jpg" alt="">
<div class="caption">Geneva</div>
</div>
<div class="image-container">
<img src="/images/image3.jpg" alt="">
<div class="caption">Paris</div>
</div>
<div class="image-container">
<img src="/images/image4.jpg" alt="">
<div class="caption">Barcelona</div>
</div>
<div class="image-container">
<img src="/images/image5.jpg" alt="">
<div class="caption">Zurich</div>
</div>
</div>
</body>
</html>