
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')
})






