Observe elements and fire callbacks on viewport enter and exit
You are tasked with implementing an Intersection Observer, a utility commonly used in frontend development to detect when an element enters or exits the viewport. Your goal is to create a class that can observe multiple elements on a webpage and trigger a callback function when these elements intersect or stop intersecting with the viewport. MDN’s Intersection Observer API guide documents the options and callback shape.
The Intersection Observer you will create should be capable of handling multiple elements simultaneously, monitoring their presence within the viewport. This feature is crucial for implementing lazy loading of images, infinite scrolling, and animations based on scroll position, enhancing user experience and performance.
To illustrate, consider a webpage with multiple sections that become visible only as the user scrolls. Your Intersection Observer should be able to detect when each section comes into view and trigger a specified callback function, allowing for dynamic content loading or animations.
Here is a basic example of how your Intersection Observer might be initialized and used:
const observer = new MyIntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log(entry.target, 'has entered the viewport');
} else {
console.log(entry.target, 'has exited the viewport');
}
});
});
// Assuming `section1` and `section2` are DOM elements you wish to observe
observer.observe(section1);
observer.observe(section2);
This implementation should efficiently manage and track the elements, ensuring that the callback function is invoked appropriately as elements enter and leave the viewport. Consider the implications of scroll events, element visibility, and the efficient use of resources in your solution.