inView
The inView
gesture triggers when an element enters and leaves the window's viewport, or the viewport of a scrollable parent element.
Detecting when an element is in view can help creating effects like:
Animating elements in when they scroll into view.
Deactivating animations when they're no longer visible.
Lazy-loading content.
Automatically start/stop videos.
Motion One's inView
function is built on the browser's native Intersection Observer API for the best possible performance (all calculations happen off the main JavaScript thread) and a tiny filesize (just 0.5kb).
Usage
Import from "motion"
:
inView
can accept either a selector, Element
, or array of Element
s.
By default, the provided callback will fire just once, when the element first enters the viewport.
This callback is provided an IntersectionObserverEntry
object which contains information on the intersection.
Leaving the viewport
A function returned from this callback will fire when the element leaves the viewport.
Additionally, the gesture will also continue to fire as the element enters/leaves the viewport.
Detect a scrollable element
By default, inView
detects when the provided element(s) enter/leave the default viewport, the browser window.
But it can also detect when the element(s) enter/leave the viewport of a scrollable parent element, by passing that element to the root
option:
Stop viewport detection
inView
returns a function that, when fired, will stop gesture detection.
Options
root
Default: window
If provided, inView
will use the root
element's viewport to detect whether the target elements are in view. Otherwise defaults to the browser window.
margin
Default: 0
A CSS margin to apply to the root viewport so an element can be considered in view sooner or later.
Can be in pixels or percentages. It can accept up to four values in the order of top/right/bottom/left.
Positive values extend the viewport boundaries beyond the root whereas negative values will pull it in.
Note: For browser security reasons, margin
won't take affect within cross-origin iframes unless root
is explicitly defined.
amount
Default: "any"
The amount of the target element that needs to be within the viewport boundaries to be considered in view.
This can be defined as "any"
, for any of the element, or "all"
, for all of the element.
Additionally, it can be defined as a number proportion between 0
and 1
where 0
is "any"
and 1
is "all".