
What Is Intersection Observer API ?
It's a web API that would help you observer an element (target) and know whether that target has intersected with the root (usually the viewport) so you can trigger certain actions based on element appearing/disappearing from the viewport. You can think about this API as someone who is constantly checking the user's viewport looking for target elements.
Read more: MDN - Intersection Observer API
What Can be Achieved Using this API ?
As mentioned in MDN:
- Lazy-loading of images or other content as a page is scrolled.
- Implementing "infinite scrolling" websites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages.
- Reporting of visibility of advertisements in order to calculate ad revenues.
- Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result.
Working with React/Next ...
Sometimes you may want to watch not just a single element and it would be helpful if you can combine the logic for that in a single place and re-use it wherever needed, So I created this custom hook to target multi elements from the DOM and listen for their intersection with the root (viewport)...
And you would use it like this:
root = null, this means the root will be the browser viewport.rootMargin, you can add margin for the root and this will trigger elements visibility either early (before) or late (after) they actually appeared in the root.threshold, this will be either a number from 0-1 or an array of numbers, it will help you define target element visibility threshold. For example 0.3 threshold will mean if the target visible for 30% in the root then fire the callback. zero means as soon as the target appears in the root, and 1 means when the target is fully (100%) visible.
You can use array of number if you want to trigger the callback multiple times for the same element after each percentage of passing the threshold. For example , will trigger the call back 3 times; as soon as the element appears, when it's 25% visible and when it's 50%.