IntersectionObserver Introduction: A Beginner’s Guide
What Is IntersectionObserver?
IntersectionObserver is a JavaScript API that asynchronously monitors whether a specific element on a web page enters the viewport (the user’s screen).
This allows you to implement dynamic visual effects based on the scroll position.
When to Use IntersectionObserver
- Lazy Loading: Prevents content such as images and videos from loading until the user actually needs them.
- Scroll Animations: Animates elements as the user scrolls the page.
- Infinite Scroll: Loads additional content when the user reaches the bottom of the page.
Advantages and Disadvantages
Advantages
- Improved Performance: Reduces unnecessary JavaScript execution.
- Better User Experience: Shortens the initial page load time through lazy loading of content.
Disadvantages
- Browser Compatibility: May not be supported in some older browsers.
- Complexity: It may be slightly difficult for beginners to understand and implement.
Implementation Demo: Changing Header Menu Color on Scroll
The following code demonstrates how to use IntersectionObserver to change the text link color of a fixed header menu when each section enters the viewport as the user scrolls through the page.
HTML Code
This HTML code includes four sections from Section 1 to Section 4, each assigned a unique ID. This allows you to monitor when each section enters or leaves the viewport using IntersectionObserver and update the style of the corresponding navigation link.
<header>
<nav>
<ul>
<li><a href="#section1">Section 1</a></li>
<li><a href="#section2">Section 2</a></li>
<li><a href="#section3">Section 3</a></li>
<li><a href="#section4">Section 4</a></li>
</ul>
</nav>
</header>
<!-- Section 1 -->
<section id="section1">
<h1>Using IntersectionObserver,<br>when each section enters the viewport as you scroll,<br>the header text link color changes.</h1>
<h2>Section 1</h2>
<p>This is the content of Section 1.</p>
</section>
<!-- Section 2 -->
<section id="section2">
<h2>Section 2</h2>
<p>This is the content of Section 2.</p>
</section>
<!-- Section 3 -->
<section id="section3">
<h2>Section 3</h2>
<p>This is the content of Section 3.</p>
</section>
<!-- Section 4 -->
<section id="section4">
<h2>Section 4</h2>
<p>This is the content of Section 4. When you scroll, the header menu link color changes.</p>
</section>
CSS
This CSS defines the styles for the header, navigation menu, and section areas. Each section is assigned a different background color to create visual distinction. This provides clear visual feedback as users scroll through each section, making it obvious that IntersectionObserver is functioning.
<style>
body {
font-size: 16px;
text-align: left;
margin: 0;
padding-top: 60px;
}
h1{
text-align: center;
font-size: 20px;
padding: 10px 0 20px 0;
line-height: 1.8em;
}
header {
position: fixed;
top: 0;
width: 100%;
background: #fff;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
z-index: 10;
}
nav ul {
list-style: none;
padding: 20px 0;
margin: 0;
display: flex;
justify-content: center;
}
nav ul li {
margin: 0 10px;
}
nav ul li a {
text-decoration: none;
color: black;
}
section {
padding: 20px;
margin: 200px 0;
border: 1px solid #ddd;
text-align: center;
}
/* Section-specific styles */
#section1 { background-color: #f9f9f9; }
#section2 { background-color: #e9e9e9; }
#section3 { background-color: #d9d9d9; }
#section4 { background-color: #c9c9c9; }
</style>
JavaScript Code (IntersectionObserver)
In this JavaScript code, each section element is observed using IntersectionObserver, and the style of the related navigation link is updated depending on whether the section enters the viewport. When a section is visible in the viewport, its corresponding link turns blue and becomes bold. When it leaves the viewport, the link returns to black with normal font weight.
<script>
document.addEventListener('DOMContentLoaded', () => {
const options = {
root: null,
rootMargin: '0px',
threshold: 1.0
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const id = entry.target.getAttribute('id');
const menuLink = document.querySelector(`nav ul li a[href="#${id}"]`);
if (entry.isIntersecting) {
menuLink.style.color = 'blue';
menuLink.style.fontWeight = 'bold';
} else {
menuLink.style.color = 'black';
menuLink.style.fontWeight = 'normal';
}
});
}, options);
// Set up the observer for each section
document.querySelectorAll('section').forEach((section) => {
observer.observe(section);
});
});
</script>
Demo Page: Header Menu Color Changes on Scroll Using IntersectionObserver
When you scroll, only the section area (among the four sections) currently visible within the viewport (browser) will have its corresponding fixed header text link changed to blue. Links for sections not visible in the viewport remain black.
You can view the implemented demo page from the link below.
Demo Page: Header Menu Color Changes on Scroll Using IntersectionObserver
Comparison with the JavaScript scroll Event
The scroll event is triggered every time the user scrolls the page. While this allows you to trigger actions at any position on the page, frequent event firing may impact performance.
IntersectionObserver monitors whether specific elements enter the viewport and executes processing only when necessary. This helps reduce performance issues while still enabling dynamic functionality.
Conclusion
IntersectionObserver is a powerful tool that offers many possibilities in modern web development. For beginner engineers, learning it is a great opportunity to understand how to improve both performance and user experience.
※If you reuse this content, please do so at your own responsibility.
Do not reuse the Google Analytics tag inside the head tag of the demo page.
