How to Use Intersection Observer in JavaScript: Simple Guide
Use the
IntersectionObserver API in JavaScript by creating a new observer with a callback function and options, then call observe() on target elements. This lets you detect when elements enter or leave the viewport without heavy scroll event listeners.Syntax
The IntersectionObserver constructor takes two arguments: a callback function and an optional options object.
- callback(entries, observer): Called when observed elements intersect with the viewport or root.
- options: Configure the root element, margin, and threshold for intersection.
Use observe(targetElement) to start watching an element.
javascript
const observer = new IntersectionObserver((entries, observer) => { entries.forEach(entry => { if (entry.isIntersecting) { console.log('Element is visible'); } }); }, { root: null, // viewport rootMargin: '0px', threshold: 1.0 // fully visible }); observer.observe(document.querySelector('#target'));
Example
This example watches a box element and logs a message when it becomes visible in the viewport.
javascript
const box = document.querySelector('#box'); const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { console.log('Box is visible on screen'); observer.unobserve(entry.target); // stop observing after visible } }); }, { root: null, // viewport rootMargin: '0px', threshold: 0.5 // 50% visible }); observer.observe(box);
Output
Box is visible on screen
Common Pitfalls
- Not calling
observe()on the target element will not trigger the callback. - Using a
thresholdvalue that doesn't match your visibility needs can cause unexpected triggers. - Forgetting to disconnect the observer with
disconnect()can cause memory leaks. - Assuming the callback runs only once; it runs every time the intersection changes.
javascript
/* Wrong: Not observing the element */ const observer = new IntersectionObserver(() => { console.log('This will never run'); }); /* Right: Observing the element */ const target = document.querySelector('#target'); observer.observe(target);
Quick Reference
| Property | Description |
|---|---|
| IntersectionObserver(callback, options) | Creates a new observer with callback and options |
| observe(element) | Starts observing the element |
| unobserve(element) | Stops observing the element |
| disconnect() | Stops observing all elements |
| root | Element used as viewport, null means browser viewport |
| rootMargin | Margin around root to grow/shrink viewport |
| threshold | Percentage of element visibility to trigger callback |
Key Takeaways
Create an IntersectionObserver with a callback and options to watch elements.
Call observe() on elements you want to track for visibility changes.
Use threshold to control how much of the element must be visible to trigger.
Remember to disconnect the observer when no longer needed to free resources.
IntersectionObserver is efficient and better than scroll event listeners for visibility.