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
As mentioned in MDN:
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)...
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 , [0, 0.25, 0.5]
will trigger the call back 3 times; as soon as the element appears, when it's 25% visible and when it's 50%.
ref
and proper id
property that is uniquely identifies it...You can see an example in my Work Experience Page , where I use intersection observer API to show and hide some text details with a little of animation as target elements appear/disappear on the viewport.
(Note: this is a low quality recording)