If you just want to run some code when an element becomes visible in the viewport:
function onVisible(element, callback) {
new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if(entry.intersectionRatio > 0) {
callback(element);
observer.disconnect();
}
});
}).observe(element);
}
When the element has become visible the intersection observer calls callback
and then destroys itself with .disconnect()
.
Use it like this:
onVisible(document.querySelector("#myElement"), () => console.log("it's visible"));