useInView

useInView is a custom hook that monitors the visibility of a DOM element and returns a reactive boolean value. This value indicates whether the element is currently within the viewport.

Usage

useInView track the visibility of a DOM element. Pass a ref of the DOM element to the hook.

<script setup>
import { useInView } from 'motion-v'

const scope = ref(null)
const isInView = useInView(scope)
</script>

<template>
  <div
    ref="scope"
    class="bg-primary p-4 rounded w-20 h-20"
  />
</template>

while the element is in the viewport, isInView.value will be true. when the element is out of the viewport, isInView.value will be false.

Options

useInView accepts an options object as the second argument.

it has the following properties:

  • once: boolean. If set to true, isInView will trigger only once and will not respond to subsequent changes in visibility.

Default: false.

const isInView = useInView(scope, {
  once: true,
})
  • root: HTMLElement. the root element to check the visibility.

Default: Window.

const isInView = useInView(scope, {
  root: document.getElementById('app'),
})
  • margin: string. the margin around the root element.

Default: 0px.

const isInView = useInView(scope, {
  margin: '100px',
})
  • amount: 'some' | 'all' | 0-1. The amount of an element that should enter the viewport to be considered in view.

Default: some.

const isInView = useInView(scope, {
  amount: 'all',
})