How to use Intersection Observer?
The Intersection Observer API allows you to monitor the visibility of an element within an ancestor or the document viewport. Here are the key components and concepts:
1. Callback Function
The callback function is triggered when the visibility of the observed elements changes. It receives a list of entries, each representing an observed element. The isIntersecting
property of each entry indicates if the element is currently visible:
true
: The target element is visible.false
: The target element is not visible.
const callback = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Element is visible:', entry.target);
} else {
console.log('Element is not visible:', entry.target);
}
});
};
2. Options Object
The options object configures the behavior of the Intersection Observer. It includes the following properties:
root
: Specifies the element used as the viewport for visibility checking. It must be an ancestor of the target element. If not specified, the document viewport is used by default.threshold
: Defines the percentage of the target element’s visibility that triggers the callback. This can be a single number or an array of numbers.- Single number: For example,
0.5
triggers the callback when 50% of the target element is visible. - Array of numbers: For example,
[0.25, 0.5]
triggers the callback when 25% and 50% of the target element are visible.
- Single number: For example,
rootMargin
: Similar to CSS margin properties, this value can shrink or grow the root viewport. It can accept one value (applied to all four sides) or multiple values (specific to each side).- Example:
20px
makes the viewport 20px larger, so the target element is considered intersecting when it is within 20px of the viewport.
- Example:
const options = {
root: document.querySelector('#scrollArea'),
threshold: [0.25, 0.5],
rootMargin: '10px 20px 30px 40px'
};
const observer = new IntersectionObserver(callback, options);
Infinite Scroll using JavaScript Intersection Observer API
The API observes the changes on the page and checks if our target element intersects with the viewport or some other element known as the root element or not. As soon as the element intersects, the API invokes a callback function. Creating an infinite scroll using the JavaScript Intersection Observer API involves detecting when the user has scrolled to the bottom (or near the bottom) of a page, and then dynamically loading more content.