detect if element is in viewport,intersection observer api,lazy-loading images,infinite scrolling,browser api

How to Detect if Element is in Viewport – Using Intersection Observer API

Hello Friends 🙏, As a Frontend developer, most of us must have got into situation where we need to 👀 detect if element is in viewport and then do some actions based on it.

This is not an easy task as it involves lot of calculations in JavaScript code 😅, which is mostly unreliable and prone to causing the browser sluggish as all those calculations run on the main thread 😵.

What is Intersection Observer API

To overcome this situation, browsers has developed Intersection Observer API 😎, this browser API asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.

Common use cases that can be acheived using this Intersection Observer API are:

  • ✅ “Lazy-loading images” or other content as a page is scrolled.
  • ✅ Implementing “infinite scrolling” web sites.

With Intersection Observer API, we can register a callback function, which gets executed whenever an element enters or exits another element or the viewport. It basically tells about the amount of the element getting intersected in percentage.

How to Detect if Element is in Viewport – Demo

To demonstrate this API 😎, we will create an example in which we will change the opacity of an element based on the amount of that element in the viewport. So if element is 100% in viewport, its opacity will be 1 and if its 50% in viewport then opacity will be 0.5 and 0 opacity if element is not visible in the viewport.

Chalo suru kiya jaye!🍻 Lets start! 🕺.

Create the element in HTML

First we will have to create an element, which will be monitor by the API.

Here we have created a <div> with id=”box” and then we have styled it to look as a square on the browser.
We also have added height to body, so that scrollbar can appear on the page.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>
      Intersection Observer API - Detecting visibility of an element on Viewport
    </title>
    <style>
      body {
        height: 1500px;
      }
      #box {
        width: 100px;
        height: 100px;
        border: 1px solid #000;
        background: blue;
      }
    </style>
  </head>
  <body>
    <div id="box"></div>
    <script src="./script.js"></script>
  </body>
</html>

Now we will start writing JS in script.js file.

Define the Target element

let target = document.querySelector("#box");

Create the Intersection Observer

Create the intersection observer, it requires two parameters: callback & options

// Create the intersection observer
let observer = new IntersectionObserver(callback, options);

Define Options for Intersection Observer

Options control the circumstances under which the observer’s callback is inoked.
We can define root, it is the element relative to which observer will start monitoring, to monitor document viewport this must be null.
rootMargin, its the bounding box of the root element, this is taken into account while computing intersections by observer.
threshold, this indicate at what percentage of the target element visibility the observer’s callback should be executed, this can be a single value or array of values.

Here we have used array of values between 0 and 1 in the threshold, so that callback gets executed whenever target element crosses the viewport by these margins.

let options = {
  root: null,
  rootMargin: "0px",
  threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1],
};

Define Callback for Intersection Observer

Callback function gets executed by the API, whenever a threshold is crossed in one direction or the other.
We get entries array in the callback, which gives lots of information about the intersection, we will use intersectionRatio information and will set the opacity of the element equal to it.

let callback = (entries, observer) => {
  entries.forEach((entry) => {
    // changing opacity of element based on its visibility on the viewport
    entry.target.style.opacity = entry.intersectionRatio;
  });
};

Start Monitoring the Target Element

observer.observe(target);

Run Application on Browser

Now try scrolling the browser and observe the box opacity, it will change as it crosses the viewport.👏🥳

detect if element is in viewport,intersection observer api,lazy-loading images,infinite scrolling,browser api

Browser Support

detect if element is in viewport,intersection observer api,lazy-loading images,infinite scrolling,browser api

Checkout the demo here.

Thanks 🙏.

Liked this tutorial? Check more here -> Browser Turorials.

1 thought on “How to Detect if Element is in Viewport – Using Intersection Observer API”

Leave a Comment

Your email address will not be published. Required fields are marked *