Created
April 27, 2023 17:44
-
-
Save kevnk/14aa9fe170fe7f627549500b35318214 to your computer and use it in GitHub Desktop.
AOS for AlpineJS
This file contains hidden or 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
/** | |
* 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