Last active
July 13, 2023 23:40
-
-
Save Therosin/7d2865499419901059cf072c14e0ee10 to your computer and use it in GitHub Desktop.
access scroll position from css
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
| /** | |
| * Creates a scroll tracker for the given document. | |
| * @param {Document} document - the document to track | |
| */ | |
| function createDocumentScrollTracker(document) { | |
| /** | |
| * store the current scroll position in a data attribute so it can be read by CSS. | |
| */ | |
| const updateScrollTracking = () => { | |
| document.documentElement.dataset.scrollX = Math.round(window.scrollX); | |
| document.documentElement.dataset.scrollY = Math.round(window.scrollY); | |
| } | |
| /** | |
| * creates a scroll event handler that will update the scroll position data attributes. | |
| */ | |
| document.enableScrollTracking = () => { | |
| let frame; | |
| const ScrollTracker = () => { | |
| if (frame) { cancelAnimationFrame(frame); } | |
| frame = requestAnimationFrame(() => { updateScrollTracking(); }); | |
| } | |
| // Listen for new scroll events. | |
| document.addEventListener('scroll', ScrollTracker, { passive: true }); | |
| // Update scroll position for first time | |
| updateScrollTracking(); | |
| } | |
| /** | |
| * removes the scroll event handler and position data attributes. | |
| */ | |
| document.disableScrollTracking = () => { | |
| document.removeEventListener('scroll', ScrollTracker); | |
| document.documentElement.removeAttribute("data-scroll-x"); | |
| document.documentElement.removeAttribute("data-scroll-y"); | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment