Created
December 8, 2023 11:39
-
-
Save johndwells/36d11204b4ff983ff5001d5a45c292ac to your computer and use it in GitHub Desktop.
SmoothScroll component built with AlpineJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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