I need to link these two codes so that when the “isElementInViewport” function returns true to trigger the “inviewport” event:
let inViewportEvent = document.createEvent("Event");
inViewportEvent.initEvent("inviewport", true, true);
document.addEventListener("inviewport", (e) => {
console.log(`${e.target} in viewport!`)
}, false);
document.dispatchEvent(inViewportEvent);
and this function to detect if a element are in viewport:
const isElementInViewport = el => {
let rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}