Docs/Functions/inView

inView

inView is an imperative wrapper around IntersectionObserver. The callback runs when an element enters; return a cleanup function to run when it leaves.

import { inView } from 'motion-solidjs'

const stop = inView(
  '.card',
  (info) => {
    info.target.classList.add('seen')
    return () => info.target.classList.remove('seen') // on exit
  },
  { amount: 0.5, margin: '0px' },
)

// later
stop()
whileInView
Card 1
Card 2
Card 3
Card 4
Card 5
Card 6
Card 7
Card 8
while-in-view.tsxOpen ↗
import { motion } from 'motion-solidjs'
import { For, createSignal } from 'solid-js'

export const meta = {
  slug: 'while-in-view',
  title: 'While in view',
  category: 'scroll',
  description: 'Each card animates as it enters the viewport.',
  tag: 'whileInView',
} as const

export default function WhileInView() {
  const [container, setContainer] = createSignal<HTMLDivElement | null>(null)
  return (
    <div
      ref={setContainer}
      class="h-64 w-56 overflow-y-scroll rounded-2xl border border-border bg-card p-4"
    >
      <For each={[0, 1, 2, 3, 4, 5, 6, 7]}>
        {(i) => (
          <motion.div
            class="mb-3 grid h-16 place-items-center rounded-2xl bg-grad-amber text-xs font-semibold text-white"
            initial={{ opacity: 0, x: -40 }}
            whileInView={{ opacity: 1, x: 0 }}
            viewport={{ root: container() ?? undefined, amount: 0.5 }}
            transition={{ type: 'spring', stiffness: 240, damping: 22 }}
          >
            Card {i + 1}
          </motion.div>
        )}
      </For>
    </div>
  )
}

For a reactive boolean, see createInView.