Created
February 7, 2022 18:00
-
-
Save pcolazurdo/d2c171efec6ae963201fac44fb48f402 to your computer and use it in GitHub Desktop.
Browser: Observe events when an element is visible in the screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var observer = new IntersectionObserver(function (entries) { | |
// isIntersecting is true when element and viewport are overlapping | |
// isIntersecting is false when element and viewport don't overlap | |
if (entries[0].isIntersecting === true) | |
console.log(entries[0].target.id); | |
}, { threshold: [0] }); | |
// Observe all H2 headings and get their id printed into the console whenever they are in focus | |
document.querySelectorAll("h2").forEach(function (item) { | |
observer.observe(document.querySelector("#" + item.id)); | |
console.log("Added observer for: #" + item.id); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment