Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Tracked mouse position gets lost when scrolling

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading