How to Create Viewport Detection With Intersection Observer API

The Intersection Observer API provides a way to monitor asynchronous changes in a target element’s intersection with a predecessor element or a top-level document viewport.

This is a tiny instance that reveals tips on how to detect if a component is within the viewport utilizing the Intersection Observer API.

How to make use of it:

1. The essential performance for ‘is in viewport’ detection.

function inViewport(elem, callback, options = {}) {
  return new IntersectionObserver(entries => {
    entries.forEach(entry => callback(entry));
  }, options).observe(document.querySelector(elem));

2. Attach the performance to the goal aspect and decide on the parent container.

<div class="box">
  <div class="scroll">
      <div class="target">Target</div>
  <span>In viewport: <strong>false</strong></span>
inViewport('.target', element => {
  // returns true or false
}, {
  root: document.querySelector('.scroll')

Viewport Detection With IntersectionObserver API

See Demo And Download

Official Website(aaroniker): Click Here

This superior jQuery/javascript plugin is developed by aaroniker. For extra Advanced Usage, please go to the official website.