Author: | Aaron Iker |
---|---|
Views Total: | 1,645 views |
Official Page: | Go to website |
Last Update: | August 20, 2020 |
License: | MIT |
Preview:

Description:
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> <div class="target">Target</div> </div> </div> <span>In viewport: <strong>false</strong></span> </div>
inViewport('.target', element => { // returns true or false }, { root: document.querySelector('.scroll') })