I’m using the following snippet to track the mouse position and to append some styles:
const blob = document.getElementById("blob");
window.onpointermove = event => {
const { clientX, clientY } = event;
blob.animate({
left: `${clientX}px`,
top: `${clientY}px`
}, { duration: 3000, fill: "forwards" });
}
Everything works as I wish until I start scrolling. Then the positions sticks to where I started scrolling and wont catch up.
You can see the demo here: https://wordpress-318817-3165474.cloudwaysapps.com/index.php/version-3/
I’m stuck and don’t know what I did wrong. I hope someone can help me out.
>Solution :
This issue is occurring because the event.clientX and event.clientY properties represent the mouse position relative to the viewport, rather than relative to the document. When you scroll, the position of the viewport changes, but the mouse position remains the same.
To fix this issue, you can add the current scroll position to the mouse position. Here’s how you can modify the code to do that:
const blob = document.getElementById("blob");
window.onpointermove = event => {
const { clientX, clientY } = event;
const left = clientX + window.scrollX;
const top = clientY + window.scrollY;
blob.animate({
left: `${left}px`,
top: `${top}px`
}, { duration: 3000, fill: "forwards" });
}
In this modified code, we’re adding window.scrollX and window.scrollY to the clientX and clientY positions, respectively, to get the absolute position of the mouse relative to the document. This should allow the blob element to follow the mouse position correctly even when you’re scrolling.
I hope this helps!