Scroll

Read and write the scroll position of an element or the window, optionally animated.

Source
Helpers demo

Line 1

Line 2

Line 3

Line 4

Line 5

Line 6

Line 7

Line 8

Line 9

Line 10

Line 11

Line 12

Line 13

Line 14

Line 15

Line 16

Line 17

Line 18

Line 19

Line 20

Line 21

Line 22

Line 23

Line 24

Line 25

Line 26

Line 27

Line 28

Line 29

Line 30

Line 31

Line 32

Line 33

Line 34

Line 35

Line 36

Line 37

Line 38

Line 39

Line 40

Installation

Usage

import { getVerticalScrollPosition, setVerticalScrollPosition } from '@/lib/scroll'

setVerticalScrollPosition(element, 0, 300)

Every function takes an element or window. Without a duration, or with 0, the position is written at once.

FunctionDescription
getVerticalScrollPosition(target)Current vertical offset.
getHorizontalScrollPosition(target)Current horizontal offset.
setVerticalScrollPosition(target, offset, duration?)Scrolls vertically, animated over duration milliseconds.
setHorizontalScrollPosition(target, offset, duration?)Scrolls horizontally, animated over duration milliseconds.
animVerticalScrollTo(target, to, duration?)The animation behind setVerticalScrollPosition.
animHorizontalScrollTo(target, to, duration?)The animation behind setHorizontalScrollPosition.
getVerticalScrollDestination(target)Where a running vertical animation is heading, or the current offset.
getHorizontalScrollDestination(target)Where a running horizontal animation is heading, or the current offset.

Animated calls on the same element and axis combine instead of fighting. A call with the destination already running changes nothing, so pressing a button twice does not slow the scroll down; a new destination adds the difference on top of the running motion, so a reversal turns smoothly. The easing is --ease-standard. The wheel, a touch drag or a scrolling key on the target stops the animation where it is, a call without a duration cancels it, and with prefers-reduced-motion: reduce every call jumps.

Changelog

No changes yet.