Search code examples
javascriptobserversintersection-observer

How to check initially if an element is intersecting using IntersectionObserver


Goal: I want to perform one action for a group of elements which are intersecting on page load and handle all others(which are currently not intersecting) individually.

Issue: Every observer has its own callback and I can't get result for a group of them synchronously.

Possible solution: If the intersection observer can be asked initially if the element is intersecting. As far as I know, there is no such functionality, so every idea or help will be appreciated.


Solution

  • There is actually a method on the IntersectionObserver class that could help you achieve your goal. It's IntersectionObserver.takeRecords(). It returns an array of observed entries that experienced intersection change.

    This method also forces IntersectionObserver to check and update intersections, so entries that are returned from this function, will have the latest intersection ratio included.

    Further reading: here