Skip to content

Instantly share code, notes, and snippets.

@Therosin
Last active July 13, 2023 23:40
Show Gist options
  • Select an option

  • Save Therosin/b14a1e94587054784d84148216c14ff1 to your computer and use it in GitHub Desktop.

Select an option

Save Therosin/b14a1e94587054784d84148216c14ff1 to your computer and use it in GitHub Desktop.
access mouse position from css
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