Skip to article

inView

inView() runs callbacks when elements enter and leave the viewport, built on IntersectionObserver.

inView detects when elements enter and leave the viewport.

inView("#carousel li", (element) => {
  animate(element, { opacity: 1 })
})

Detecting when an element is in view can help creating effects like:

  • Animating elements when they scroll into and out of view.

  • Deactivating animations when they're no longer visible.

  • Lazy-loading content.

  • Automatically start/stop videos.

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).

Scroll-triggered animationOpen example

Usage

Import from "motion":

import { inView } from "motion"

inView can accept either a selector, Element, or array of Elements.

// Selector
inView("section", callback)

// Element
const box = document.getElementById("box")
inView(box, callback)

By default, the provided callback will fire just once, when the element first enters the viewport.

inView(element, () => {
  console.log