Hide and Seek with Intersection Observer

Hide and Seek with Intersection Observer

Let's Play Hide and Seek and learn something new

ยท

6 min read

I hope everyone has played Hide and Seek in their childhood. It has specific area (viewport) to play , a target to find, and one observer to watch. Similarly here at web pages, We also have to do the same. Sometimes we need to find ๐Ÿ” if div is visible in the viewport or not.

What is View Port

By not making it very complicated, the viewport is the area of the web page that is visible to user, Now for a desktop user it is large and small for mobile devices, depends on the devices on which they are checking the webpage

Intersection Observer API

Coming Back to point, so I will check whether a div/span/id or any querySelector is in the viewport or not, Such that I can do something e.g., show an alert that "I can see you ", I will not follow the old one getBoundingClientRect to find the height, width, x, y and so on. I will use the new Intersection Observer API. As in hide and seek , we need to find the particular person. Here let's call the div target to watch if it is visible in the viewport (house ). So Intersection Observer (i.e., you )observes the target, calls a callback/function (to do something ) if the target comes in the viewport or matches the given options (condition), its a simple object to define the matching condition for the target, So it's clear that:-

  • We need options (condition to be matched to run callback)
  • We need a callback (to do something )
  • We need a target to observe & then at last simple observe
let options = {
  root: null, 
  rootMargin: '0px',
  threshold: 1.0
}
let callback = (entries, observer) => {
  entries.forEach(entry => {
    // you can check here by entry.isIntersecting
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.boundingClientRect
    //   entry.intersectionRatio
    //   entry.intersectionRect
    //   entry.isIntersecting
    //   entry.rootBounds
    //   entry.target
    //   entry.time
  });
};
let observer = new IntersectionObserver(callback, options);
let target = document.querySelector('#xyz')
observer.observe(target);

Now as this xyz, matches our options (condition) , a callback will be called to take some action, there we have different parameters to work with we can check by entry. intersecting or not .

I know you must be confused about the options keys , lets discuss it one by one .

let options = {
  root: null, 
  rootMargin: '0px',
  threshold: 1.0
}

Here root - is the viewport/zone in which we want to oberve the target element , by default if its not given, it is considered as null that will be viewport itself

Note that root should always be the parent of your target element

rootMargin is the margin of the root for viewport its 0px, you can specify according to your need here

threshold: this is a very interesting property as it's defined from

  • 0 - for even if the single pixel is visible, fire the callback, by default = 0
  • 1 - for full div is visible then fire the callback
  • 0.5 - for 50% visibility

Real Application of Intersection Observer

  • Can fire up analytics based upon if the ad-div is visible or not
  • Can lazy load images if they are in the viewport
  • Can make infinite fetch calls
  • CSS Animation
  • Lazy load react components

Created a simple day-night watcher, Check how displayed text is changed to day and night , based upon the weather day querySelector is 50% viewport

let target = document.querySelector('.day')
let options = {
    threshold: 0.5,
    root: null,
    rootMargin: '0px'
}
let callback = (entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            document.getElementById('display-meter').innerHTML = "Day";
        } else {
            document.getElementById('display-meter').innerHTML = 'Night';
        }
    });
};
let observer = new IntersectionObserver(callback, options)
observer.observe(target)

Webp.net-gifmaker (1).gif

Please feel free to share and also you can comment for any Improvements to this article, Thanks

Did you find this article valuable?

Support Vivek Gautam by becoming a sponsor. Any amount is appreciated!

ย