Svelte action that listens for click events and scrolls to elements with animation. Inspired by rigor789/vue-scrollto.
npm install svelte-scrolltoAnimating vertical and horizontal scrolling
``bash`
npm install --save-dev svelte-scrolltoor
yarn add -D svelte-scrollto
`html
animateScroll.scrollToBottom()}> Scroll to bottom
animateScroll.scrollToTop()}> Scroll to top
animateScroll.scrollTo({element: 'scroll-to-element-selector'})}> Scroll to element
animateScroll.scrollTo({element: 'scroll-to-element-selector', offset: 200})}> Scroll to below element 200px
animateScroll.scrollTo({element: 'scroll-to-element-selector', duration: 2000})}> Scroll to element over 2000ms
`
Using as a action
`html`
Scroll to element
| Option | Required | Default value | Description |
| :------------: | :------: | :-----------: | :---------: |
| container | â | "body" | Scroll container duration
| | â | 500 | The duration (in milliseconds) of the scrolling animation.delay
| | | 0 |offset
| | | 0 | The offset that should be applied when scrolling. This option accepts a callback functioneasing
| | | cubicInOut | The easing function to be used when animating. Can pass any easing from svelte/easing or pass custom easing function.onStart
| | | noop | A callback function that should be called when scrolling has started. Receives the target element and page offset as a parameter.onDone
| | | noop | A callback function that should be called when scrolling has ended. Receives the target element and page offset as a parameter.onAborting
| | | noop | A callback function that should be called when scrolling has been aborted by the user (user scrolled, clicked etc.). Receives the target element and page offset as parameters.scrollX
| | | false | Whether or not we want scrolling on the x axisscrollY
| | | true | Whether or not we want scrolling on the y axis
Override global options:
`javascript
import * as animateScroll from "svelte-scrollto";
animateScroll.setGlobalOptions({
offset: 200,
onStart: (element, offset) => {
if(element) {
console.log("Start scrolling to element:", element);
} else if(offset) {
console.log("Start scrolling to page offset: (${offset.x}, ${offset.y})");
}
}
})
`
#### scrollTo(options)element
Accepts all global options and:
+ : The element you want scroll tox
+ : The offset we want to scrolling on the x axisy
+ : The offset we want to scrolling on the y axis
#### scrollToTop(options)
Shortcut of use scrollTo with x equal to 0.
#### scrollToBottom(options)
Shortcut of use scrollTo with x equal to containerHeight
Svelte action that listens for click (touchstart) events and scrolls to elements with animation.
+ scrollto
+ scrolltotop
+ scrolltobottom`
If you want to use Lazy and want to scroll to elements, you need to give your lazy components (images, v.v..) fixed dimensions, so the browser known the size of the not loaded elements before scrolling.
[easing]: https://github.com/sveltejs/svelte/blob/master/src/runtime/easing/index.ts