Open purushothaman-source opened 2 years ago
we will get these field when the callback triggers
boundingClientRect
is the actual size of the elementintersectionReact
is the visible sizeintersectionRatio
is the actual percentage of how much the element is visible on the screenrootBound
is the root element ..By default, the root element is the screen target
is the actual element that we observing By default Threshold will be 0.. it means the callback function will get a trigger as soon as 1px get into the screen or move out of the screen..
Possible values : 0 to 1 ..
1 means function will trigger only when full element is visible or full element left the screen
You can also pass an array to threshold which means that the Intersection Observer will fire each time your element passes one of the thresholds passed to it.
const observer = new IntersectionObserver(entries => {
entires.forEach(entry => {
entry.target.innerText = `${Math.round(entry.intersectionRatio * 100)}%`
})
}, { threshold: [0, .25, .5, .75, 1] })
It is used to shrink or enlarge the container size -ve value will shrin +ve value will enlarge ..this will be useful to fetch or animate the elements before its visble
const observer = new IntersectionObserver(
changeColor,
{ rootMargin: "50px" }
)
It is actually used to use the custom container instead of body
const observer = new IntersectionObserver(
changeColor,
{ root: <container> }
)
``
It is important to stop observing elements when they no longer need to be observed, such as after they are removed from the page or after lazy loading an image in order to avoid memory leaks or performance issues. This can be done with the unobserve method or the disconnect method which are both methods on the Intersection Observer. The unobserve method takes a single element as its only parameter and it stops observing that single element. The disconnect method takes no parameters and will stop observing all elements.
new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
lazyLoadImage(entry)
observer.unobserve(entry.target)
}
})
})
Intersection Observer
Use cases : from lazy loading images, to scroll based animations
Blog
https://blog.webdevsimplified.com/2022-01/intersection-observer/
Videos
Syntax
Resizer Observer
Resizer Observer
Blog
https://blog.webdevsimplified.com/2022-01/resize-observer/
Mutation Observer