IntersectionObservers function let you know when an observed element enters or exits the browser’s viewport.

IntersectionObservers let you know when an observed element enters or exits the browser’s viewport, this feature is available in Chrome 51 (which you can get test using Chrome Canary).

You might want to do this so you can lazy-load images just in time or because you need to know if the user is actually looking at a certain ad banner. You can do that by hooking up the scroll event or by using a periodic timer and calling getBoundingClientRect() on that element. This approach, however, is painfully slow as each call toget BoundingClientRect() forces the browser to re-layout the entire page and will introduce considerable jank to your website. Matters get close to impossible when you know your site is being loaded inside an iframe and you want to know when the user can see an element.

How use it

The api is really clear and easy to use, an IntersectionObserver object will be created using new IntersectionObserver().

var callback = function(elementLocationInformation){
    console.log(elementLocationInformation);
};
var settings = {
   // The root to use for intersection.
  // If not provided, use the top-level document’s viewport.
  root : null,
  // Same as margin, can be 1, 2, 3 or 4 components, possibly negative lengths.  
  // If an explicit root element is specified, components may be percentages of the
  // root element size.  If no explicit root element is specified, using a percentage
  // is an error.
  rootMargin : "0px",
  // Threshold(s) at which to trigger callback, specified as a ratio, or list of
  // ratios, of (visible area / total area) of the observed element (hence all
  // entries must be in the range [0, 1]).  Callback will be invoked when the visible
  // ratio of the observed element crosses a threshold in the list.
  threshold : [0]
};

var IO = new IntersectionObserver(callback,settings);

The callback will be triggered a single time when the observed element comes partially into view and another time when it has left the viewport. This way IntersectionObserver gives you an answer to the question, “Is element X in view?”.

Observe

The following code shows how to observe an element using the observe method from the return IntersectionObserver object :

var io = new IntersectionObserver(
    function(entries){
       if(entries[0].intersectionRatio){
          console.log("Is visible on scroll ! See more info using console.log");
          console.log(entries[0].intersectionRect);
       }else{
          console.log("Is not visible");
       }
     }
);
// Start observing an element
io.observe(document.getElementById("myImaginaryId"));

The entries element will be an array with an object with the following structure :

IntersectionObserver

Unobserve

Note that the element needs to be previously observed, then use the unobserve method. You can reanudate the process using observe function again.

io.unobserve(document.getElementById("myImaginaryId"));

Disable observation

To disable entire IntersectionObserver, use the disconnect method.

io.disconnect();

For what should i use this function

IntersectionObservers were designed specifically with ads services and social network widgets in mind, which frequently use iframes and could benefit from knowing whether they are in view (to enhance many things). If an iframe observes one of its elements, both scrolling the iframe as well as scrolling the window containing the iframe will trigger the callback at the appropriate times. However, rootBounds will be set to null to avoid leaking data across origins.

For what shouldn't i use this function

You need to know that IntersectionObservers are intentionally neither pixel perfect nor low latency. Using them to implement things like like scroll-dependent animations are bound to fail, as the data will be – strictly speaking – out of date by the time you’ll get to use it. The explainer has more details about the original use cases for IntersectionObserver.

You can get more information about this api and for what should it be used and how use it reading the following readme file, besides read more about this feature in the original Google Article here.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors