svelte-scrolling
Version:
Scroll to given elements with smooth animation
113 lines (72 loc) • 3.04 kB
Markdown
[![npm][npm-shields]](https://www.npmjs.com/package/svelte-scrolling)
[![license][license-shields]](https://github.com/valmisson/svelte-scrolling/blob/main/LICENSE)
Scroll to given elements with smooth animation.
```bash
yarn add svelte-scrolling
```
```html
<script>
import { scrollTo, scrollRef, scrollTop } from 'svelte-scrolling'
</script>
<nav>
<a use:scrollTo={'home'}>Home</a>
<a use:scrollTo={'about'}>About</a>
<a use:scrollTo={{ ref: 'blog', duration: 1000 }}>Blog</a>
</nav>
<section use:scrollRef={'home'}></section>
<section id="about"></section>
<section use:scrollRef={'blog'}></section>
<ScrollTop>
<button on:click={() => scrollTop()}>Go to top</button>
</ScrollTop>
```
This action listens for click (touchstart) events and scrolls to elements with smooth animation. The element to scroll to must be referenced using the `scrollRef` action or `id`.
Accepts as parameter only the element reference or all global options:
- `ref`: Element reference.
*To set the global options, the `ref` property is required*
#### `scrollRef={reference}`
This action adds a reference to the elements that `scrollTo` should scroll.
Accepts as parameter a string with the name to reference the element
Scroll to the top of the page
Scroll to the end of the page
Scroll to the end of left the page
Scroll to the end of right the page
Scroll to element with smooth animation.
Scroll to a position on the page
| Property | Default | Description |
|:--------:|:-------:|:-----------:|
| `duration` | `500` | Duration (in milliseconds) of the animation. |
| `offset` | `0` | Offset that should be applied when scrolling. |
| `easing` | `cubicInOut` | Easing function to be used when animating. Use any easing from [`svelte/easing`][svelte-easing] or a custom easing function. |
| `passive` | `false` | A boolean value that, if true, indicates that the function specified by listener will never call preventDefault(). |
| `onStart` | `noop` | A callback function that should be called when scrolling has started. Receives the element, offset, duration and endPosition as a parameter. |
| `onDone` | `noop` | A callback function that should be called when scrolling has started. Receives the element, offset, duration and endPosition as a parameter. |
### Override global options
```html
<script>
import { setGlobalOptions } from 'svelte-scrolling'
setGlobalOptions({
duration: 800
})
</script>
```
[](LICENSE)
Copyright (c) 2021-present, Valmisson Grizorte
[]: https://img.shields.io/npm/v/svelte-scrolling.svg
[]: https://img.shields.io/badge/license-MIT-green
[]: https://svelte.dev/docs/svelte/svelte-easing