Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To verify if a page is at the top using IntersectionObserver, you can create a new instance of IntersectionObserver and provide it with a callback function that will be called each time the observed element intersects or disconnects from the viewport. In the callback function, you can check the entry object of the observed element to see if it is intersecting the top of the viewport.

Here is an example code snippet that demonstrates how to use IntersectionObserver to check if a page is at the top:

const observer = new IntersectionObserver(entries => {
  const [entry] = entries;
  if (entry.isIntersecting && entry.intersectionRatio === 1) {
    console.log('Page is at the top');
  }
});

const targetElement = document.querySelector('body');
observer.observe(targetElement);

In this example, we create a new IntersectionObserver instance and provide a callback function that will be called each time the observed element (in this case the body element) intersects or disconnects from the viewport.

Inside the callback function, we check if the entry object of the observed element is intersecting (i.e., visible in the viewport) and if the intersectionRatio is 1 (i.e., the entire element is visible). If both conditions are true, we log a message to the console indicating that the page is at the top.

Finally, we call the observe() method of the IntersectionObserver instance to start observing the targetElement (i.e., the body element).