Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Last active August 23, 2024 21:50
Show Gist options
  • Save james2doyle/9fca2546f0cb798f70c744242402ffeb to your computer and use it in GitHub Desktop.
Save james2doyle/9fca2546f0cb798f70c744242402ffeb to your computer and use it in GitHub Desktop.
An Alpinejs plugin that lets you trigger an expression if the page is being scrolled up or down
// USAGE:
// x-data="{ direction: 'up' }" x-scrolled.up="direction = 'up'" x-scrolled.down="direction = 'down'"
Alpine.directive(
'scrolled',
(_, { modifiers, expression }, { evaluateLater, cleanup }) => {
const results = evaluateLater(expression);
let scrollPos = 0;
const handler = () => {
const direction =
document.body.getBoundingClientRect().top > scrollPos
? 'up'
: 'down';
if (modifiers.includes(direction)) {
results();
}
// saves the new position for iteration.
scrollPos = document.body.getBoundingClientRect().top;
};
window.addEventListener('scroll', handler);
cleanup(() => {
window.removeEventListener('scroll', handler);
});
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment