Skip to content

Window Scroll

Reactive window scroll.

๐ŸŽฌ Usage

<script>
    import { window_scroll } from "@sveu/browser"

    const { x, y } = window_scroll()
</script>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

โ†ฉ๏ธ Returns

Name Description Type
x A readable store with the x position Readable<number>
y A readable store with the y position Readable<number>

๐Ÿงช Playground

Source Code ๐Ÿ‘€

Source Code
import { browser, to_readable, to_writable } from "@sveu/shared"

import { on } from "../event_listener"

/**
 * Reactive window scroll.
 *
 * @returns
 * - `x`: A readable store with the current window scroll x position.
 * - `y`: A readable store with the current window scroll y position.
 */
export function window_scroll() {
    if (!browser) return { x: to_readable(0), y: to_readable(0) }

    const x = to_writable(window.scrollX)

    const y = to_writable(window.scrollY)

    on(
        window,
        "scroll",
        () => {
            x.set(window.scrollX)
            y.set(window.scrollY)
        },
        {
            capture: false,
            passive: true,
        }
    )

    return { x: to_readable(x), y: to_readable(y) }
}

Last update: 2023-03-16