In browsers that support the Intersection Observer, this library lets you find out when an element of yours is in viewport. The viewport itself is configurable. It can be the window or any other element in the DOM. Only requirement is that the element who visibility you want to check must be a child of the element you choose as your viewport.
npm install observe-element-in-viewport
// to use window as viewport, pass this option as nullconst viewport = document// element whose visibility we want to trackconst target = document// handler for when target is in viewportconst inHandler = console// handler for when target is NOT in viewportconst outHandler = console// the returned function, when called, stops tracking the target element in the// given viewportconst unobserve =
One time query to check if
target element is in viewport
// element whose visibility we want to trackconst target = document// Using window as viewport, it will check the target element's// visibility and log true or false.// This function accepts a second parameter which is the same// as the first parameter to observeElementInViewport fn i.e.,// the options object.console