Skip to content

Instantly share code, notes, and snippets.

@kevnk
Created April 27, 2023 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevnk/14aa9fe170fe7f627549500b35318214 to your computer and use it in GitHub Desktop.
Save kevnk/14aa9fe170fe7f627549500b35318214 to your computer and use it in GitHub Desktop.
AOS for AlpineJS
/**
* Installation and setup:
* 0. Install AlpineJS: `npm i -S alpinejs`
* 1. Install AOS (we're just using their CSS): `npm i -S aos`
* 2. Make sure AlpineJS is running by adding `x-data` attribute on opening `<body>` tag
* 3. Add `x-aos:fade-up` on element to add animation
* 4. Override defaults (500ms duration and 'ease-out-cubic' easing) by passing object of options in the expression:
* eg. `x-aos:fade-up="{duration:2000,easing:'linear'}"`
*/
import Alpine from 'alpinejs';
import 'aos/dist/aos.css';
Alpine.directive('aos', (el, { value, modifiers, expression }, { evaluate, cleanup }) => {
el.setAttribute('data-aos', value);
let aosOptions = {
easing: 'ease-out-cubic',
duration: 500,
};
if (expression) {
let overrideOptions = evaluate(expression);
if (!!overrideOptions && overrideOptions.constructor === Object) {
aosOptions = {
...aosOptions,
...overrideOptions,
};
}
}
Object.keys(aosOptions).forEach((key) => {
el.setAttribute(`data-aos-${key}`, aosOptions[key]);
});
let classes = ['aos-animate'];
let observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio === 0) {
el.classList.remove(...classes);
return;
}
el.classList.add(...classes);
modifiers.includes('once') && observer.disconnect();
});
});
observer.observe(el);
cleanup(() => {
observer.disconnect();
});
});
Alpine.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment