IntersectionObserver

IntersectionObserver is a very simple and powerful browser API, it really good to build such as lazy-load images, contents or whatever, the concept is really simple, it observer an element, when is visible and then you do something about it. One example, when this div is visible then load image. Outthought its not supported by all browsers at current state, but its well supported by chrome and firefox, and thats enough for now :D.

intserctionObserver

so question is how do you use it?

all you need to do is simple, create an observer

  var observer = new IntersectionObserver(callback, options);

options has 3 different properties which you can use:

  var options = {
    root: ""
    rootMargin: "0px"
    threshold: 0.1,
  }

root: An Element object which is an ancestor of the intended target, whose bounding rectangle will be considered the viewport. Any part of the target not visible in the visible area of the root is not considered visible.

rootMargin: A string which specifies a set of offsets to add to the root’s bounding_box when calculating intersections, effectively shrinking or growing the root for calculation purposes. The syntax is approximately the same as that for the CSS margin property; see The root element and root margin in Intersection Observer API for more information on how the margin works and the syntax. The default is “0px 0px 0px 0px”.

threshold: Either a single number or an array of numbers between 0.0 and 1.0, specifying a ratio of intersection area to total bounding box area for the observed target. A value of 0.0 means that even a single visible pixel counts as the target being visible. 1.0 means that the entire target element is visible. See Thresholds in Intersection Observer API for a more in-depth description of how thresholds are used. The default is a threshold of 0.0.

so all you need to do is observer that this element is visible, do something in callback, but you need to attach the element to this observer when is 10% visible.

so lets attach the element:

  var options = {
    root: ""
    rootMargin: "0px"
    threshold: 0.1,
  }

  var observer = new IntersectionObserver(callback, options);
  observer.observe(document.queryElementById("myElement"));

now you have an element observed, but we have not add callback, so lets do that:

  var options = {
    root: ""
    rootMargin: "0px"
    threshold: 0.1,
  }

  var callback = function(entries) {
    entries.forEach(function(entry) {
      if (entry.intersectionRatio > 0) {
        // do something here.
      }
    })
  }

  var observer = new IntersectionObserver(callback, options);
  observer.observe(document.queryElementById("myElement"));

there you go, easy and powerful.