Skip to content

Instantly share code, notes, and snippets.

@pcolazurdo
Created February 7, 2022 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcolazurdo/d2c171efec6ae963201fac44fb48f402 to your computer and use it in GitHub Desktop.
Save pcolazurdo/d2c171efec6ae963201fac44fb48f402 to your computer and use it in GitHub Desktop.
Browser: Observe events when an element is visible in the screen
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