IntersectionObserver
Watches element visibility relative to a root.
IntersectionObserver and ResizeObserver let code react to visibility and size changes without constant polling.
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => console.log(entry.isIntersecting));
});
observer.observe(section);
Browser APIs & BOM
IntersectionObserver reports when an element enters or leaves a viewport or root area. It is useful for lazy loading, reveal effects and analytics triggers.
ResizeObserver reports when an element changes size. It is useful for components that respond to their own container, not the whole viewport.
Observers should be disconnected when no longer needed.
Watches element visibility relative to a root.
Watches element size changes.
Starts watching a target.
Stops observing and cleans up.
Examples
const observer = new IntersectionObserver(entries => {
entries.forEach(handleEntry);
});
observer.observe(target);
window.addEventListener("scroll", () => {
document.querySelectorAll("section").forEach(checkPosition);
});
Code patterns
These examples focus on practical browser APIs: URL state, storage, cookies, clipboard, permissions, observers and offline-capable platform tools.
Watch when an element enters view.
const observer = new IntersectionObserver(entries => {
for (const entry of entries) {
entry.target.classList.toggle("is-visible", entry.isIntersecting);
}
});
Start watching a target.
observer.observe(section);
React to element size changes.
const resizeObserver = new ResizeObserver(entries => {
console.log(entries[0].contentRect.width);
});
Disconnect when feature ends.
observer.disconnect(); resizeObserver.disconnect();
Rules that matter
Browser APIs are powerful because they touch privacy, navigation, storage, permissions and performance. Use them deliberately.
Avoid constant scroll calculations.
Viewport resize is not enough for component layouts.
Clean up when targets are removed.
Observer callbacks still run on the main thread.
They control when intersection changes fire.
Important content should not rely on reveal effects.
Production thinking
Observers let the browser tell you when something changes instead of forcing you to keep checking.
Reveal effects should not hide content from keyboard users or screen readers.
Production observer code is common for lazy loading, analytics and responsive components.
Lazy content should still be crawlable or load reliably before users need it.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
If you can explain support, permissions, fallback and cleanup, you are ready to use the API responsibly.
Senior audit upgrade