A magic helper to scroll to a target selector or offset.
As script tag, include the <script>
tag in the <head>
of your document just before Alpine:
<script src="https://cdn.jsdelivr.net/npm/alpinejs-toolkit/dist/scroll/cdn.min.js" defer></script>
As module:
import Alpine from 'alpinejs';
import Scroll from 'alpinejs-toolkit/scroll';
Alpine.plugin(Scroll);
Alpine.start();
The helper accepts:
- A
string
(representing a selector) or anumber
(pixels) - An optional
object
of options (see below)
<button x-data @click="$scroll('body')">
Scroll top
</div>
Note
Options are always merged, with the magic options having an higher priority.
Option | Default | Description |
---|---|---|
behavior |
smooth |
Determines the scrolling behavior (auto, smooth or instant ) |
Pass options when using the script tag:
<script>
window.AlpineScrollOptions = { behavior: 'instant' };
</script>
Pass options when using the module:
Alpine.plugin(Scroll.withDefaults({ behavior: 'instant' }));
Pass options for a given magic usage:
<button x-data @click="$scroll('main', { behavior: 'instant' })">
<!-- ... -->
</button>