Last active
August 23, 2024 21:50
-
-
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
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
// 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