Is In Viewport Detection With IntersectionObserver API

Category: Javascript | August 20, 2020
Author:Aaron Iker
Views Total:1,611 views
Official Page:Go to website
Last Update:August 20, 2020


Is In Viewport Detection With IntersectionObserver API


This is a tiny example that shows how to detect if an element is in the viewport using the Intersection Observer API.

How to use it:

1. The main function 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 function to the target element and determine 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')

You Might Be Interested In:

Leave a Reply