inView() function triggers callbacks when elements enter or leave the viewport using the Intersection Observer API. Perfect for lazy loading, triggering animations, and tracking visibility.
Function Signature
Parameters
element
Target element(s) to observe:- CSS selector string (e.g.,
".box","#element") - Element reference
- Multiple elements via selector
onStart
Callback when element enters viewport:InViewOptions
Return Value
Returns a cleanup function to disconnect the observer:Basic Usage
Simple Detection
Enter and Exit
With Animation
Reversible Animation
Options
Visibility Amount
Margin (Offset)
Trigger before element enters viewport:Custom Root
Observe within a scrollable container:Examples
Lazy Load Images
Stagger Entrance
Count Up Animation
Fade In on Scroll
Video Auto-Play
Slide In Sections
Progress Indicator
Parallax Background
Class Toggle
One-Time Animation
Multiple Elements
Trigger Early
Track Visibility State
Advanced Usage
With IntersectionObserverEntry
Conditional Animations
Cleanup
Performance Tips
- Set initial styles in CSS to avoid layout shift
- Use
marginto trigger animations slightly before viewport entry - Batch animations when possible using selectors
- Clean up observers when components unmount
- Use
amount: "all"sparingly - can cause jank on large elements
Margin Format
Themargin option uses CSS margin syntax:
Browser Support
- Uses native Intersection Observer API
- Supported in all modern browsers
- Falls back gracefully in older browsers (no observation)
- Polyfill available for older browsers if needed
Comparison with scroll()
| Feature | inView() | scroll() |
|---|---|---|
| Purpose | Detect visibility | Link to scroll progress |
| Trigger | Enter/exit viewport | Continuous scroll updates |
| Performance | Optimized with IO | RequestAnimationFrame |
| Use case | Lazy load, trigger | Parallax, progress bars |