Skip to content

Instantly share code, notes, and snippets.

@johndwells
Created December 8, 2023 11:39
Show Gist options
  • Save johndwells/36d11204b4ff983ff5001d5a45c292ac to your computer and use it in GitHub Desktop.
Save johndwells/36d11204b4ff983ff5001d5a45c292ac to your computer and use it in GitHub Desktop.
SmoothScroll component built with AlpineJS
/**
* Given a query selector, will use native smooth scrolling to scroll to element.
*
* Usage:
* import smoothscroll from 'path/to/smoothscroll.js';
* import Alpine from 'alpinejs';
* Alpine.data("smoothscroll", smoothscroll);
* Alpine.start();
* ...
* <button x-data="smoothscroll('#main')">Scroll to #main div</button>
*/
export default (selector = null) => ({
el: null,
selector: selector,
init() {
if(!this.selector) {
return;
}
this.el = document.querySelector(this.selector);
if(!this.el) {
return;
}
this.$el.addEventListener('click', () => {
this.el.scrollIntoView({
behavior: "smooth"
});
});
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment