Skip to content
On this page

useScroll

The scroll event.

Parameters

typescript
import { useScroll } from "@elonehoo/pistachio"

const scroll = useScroll()
const scroll = useScroll(wait)
const scroll = useScroll(options, wait?)
const scroll = useScroll(element, options?, wait?)
import { useScroll } from "@elonehoo/pistachio"

const scroll = useScroll()
const scroll = useScroll(wait)
const scroll = useScroll(options, wait?)
const scroll = useScroll(element, options?, wait?)
ParametersTypeRequiredDefaultDescription
elementRef<Element> | ElementfalsewindowDOM element used to track scroll position
optionsboolean | AddEventListenerOptionsfalse{passive: true}Listener options
waitnumberfalseundefinedDebounce event in ms

TIP

If no element is passed it will use window to get the scroll of the page

State

typescript
import { useScroll } from "@elonehoo/pistachio"

const { scrollTop, scrollLeft } = useScroll()
import { useScroll } from "@elonehoo/pistachio"

const { scrollTop, scrollLeft } = useScroll()
StateTypeDescription
scrollTopnumberScroll top position, if value is set it will call scrollTopTo
scrollLeftnumberScroll let position, if value is set it will call scrollLeftTo

Methods

typescript
import { useScroll } from "@elonehoo/pistachio"

const { remove, scrollTo, scrollLeftTo, scrollTopTo } = useScroll()
import { useScroll } from "@elonehoo/pistachio"

const { remove, scrollTo, scrollLeftTo, scrollTopTo } = useScroll()
SignatureDescription
removeManually removes the event listener
scrollToSame as calling element.scrollTo()
scrollBySame as calling element.scrollBy()
scrollIntoViewSame as calling element.scrollIntoView()
scrollLeftToCalls scrollTo with left argument
scrollTopToCalls scrollTo with top argumen

Example

Scroll

top: 0

left: 0

1

2

3

4

5

6

7

8

9

10

vue
<script setup lang="ts">
import { ref } from 'vue'
import { useScroll } from '@elonehoo/pistachio'
const elref = ref(null)

const { scrollTop, scrollLeft, remove } = useScroll(elref)
</script>

<template>
  <div>
    Scroll
    <p>top: {{ scrollTop }}</p>
    <p>left: {{ scrollLeft }}</p>
    <div ref="elref" style="overflow:scroll;height:70px;background:gray">
      <p v-for="x in 10" :key="x">
        {{ x }}
      </p>
    </div>
    <button @click="remove">
      remove
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useScroll } from '@elonehoo/pistachio'
const elref = ref(null)

const { scrollTop, scrollLeft, remove } = useScroll(elref)
</script>

<template>
  <div>
    Scroll
    <p>top: {{ scrollTop }}</p>
    <p>left: {{ scrollLeft }}</p>
    <div ref="elref" style="overflow:scroll;height:70px;background:gray">
      <p v-for="x in 10" :key="x">
        {{ x }}
      </p>
    </div>
    <button @click="remove">
      remove
    </button>
  </div>
</template>

Released under the MIT License.