Chapter 120: useScroll
Core Idea
Create Vue scroll-linked animations like progress bars & parallax with Motion for Vue's useScroll hook. Track scroll, element position & use motion values.
Key Concepts
- Page scroll: By default
- Element scroll: To track the scroll position of a scrollable element we can pass the element's ref to useS
- Element position: We can track the progress of an element as it moves within a container by passing its ref
- Scroll offsets: With the offset option we can define which parts of the element we want to track with the viewport
- Find & fix animation performance issues with your agent.: MotionScore for Agents grades animations in your source code S to F and hands your agent s
- API: useScroll accepts the following options.
- container: Default: Browser window
- target: By default
- axis: Default: "y"
Code Examples
<script setup>
const { scrollYProgress } = useScroll()
</script>
<template>
<motion.div :style="{ scaleX: scrollYProgress }" />
</template>
- What it demonstrates: Core usage pattern for useScroll.
Anti-patterns
- Note from docs: Since
scrollY is a MotionValue, there's a neat trick you can use to tell when the user's scroll direction changes:
- Note from docs: ```
- Note from docs: <script setup>
- Note from docs: const { scrollY } = useScroll()
Key Takeaways
scrollX/Y: The absolute scroll position, in pixels.
scrollXProgress/YProgress: The scroll position between the defined offsets, as a value.
- useScroll supports Page scroll.
Connects To
- Motion values: related Motion doc page.
- Vue scroll animation: related Motion doc page.
- Vue animations with Motion for Vue: related Motion doc page.
- Parallax example & tutorial for React: related Motion doc page.