Last active
July 13, 2023 23:40
-
-
Save Therosin/b14a1e94587054784d84148216c14ff1 to your computer and use it in GitHub Desktop.
access mouse 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
| function createDocumentMouseTracker(document) { | |
| /** | |
| * store the current mouse position in a data attribute so it can be read by CSS. | |
| */ | |
| const updateMouseTracking = (e) => { | |
| document.documentElement.dataset.mouseX = Math.round(e.clientX); | |
| document.documentElement.dataset.mouseY = Math.round(e.clientY); | |
| } | |
| document.enableMouseTracking = () => { | |
| let frame; | |
| MouseTracker = () => { | |
| if (frame) { cancelAnimationFrame(frame); } | |
| frame = requestAnimationFrame(() => { updateMouseTracking(); }); | |
| } | |
| // Listen for new mousemove events. | |
| document.addEventListener('mousemove', MouseTracker, { passive: true }); | |
| } | |
| document.disableMouseTracking = () => { | |
| // stop listening for new mousemove events. | |
| document.removeEventListener('mousemove', MouseTracker); | |
| document.documentElement.removeAttribute("data-mouse-x"); | |
| document.documentElement.removeAttribute("data-mouse-y"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment