Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element following mouse movement and scroll

I'm trying to write a bit of Vanilla Javascript to make an element follow my mouse movements. I've used clientX, clientY and the mousemove event to make it follow, but when I scroll the page the element doesn't move with the mouse. I thought maybe I'd need to use the scroll event but I'm struggling to make it work. Any help would be great, thanks!

document.addEventListener('mousemove', (e) => {
    const mouseFollow = document.getElementById('mouse-follow');
    const x = e.clientX - 25; //-25 to center div over mouse
    const y = e.clientY - 25; 

    mouseFollow.style.top = `${y}px`;
    mouseFollow.style.left = `${x}px`;
})
like image 986
pshaw20 Avatar asked Oct 19 '25 04:10

pshaw20


1 Answers

  • Use position: fixed;. clientX/Y is relative to the viewport, so is CSS position fixed.
  • Cache your selector, there's no need to query the DOM for an element on every mouse move

const elPointer  = document.querySelector("#pointer");

addEventListener("mousemove", (evt) => {
  elPointer.style.cssText = `
    left: ${evt.clientX}px;
    top:  ${evt.clientY}px;
  `;
});
body { /* DEMO scrollbars */ min-height: 200vh; }

#pointer {
  position: fixed;
  padding: 20px;
  background: #f0b;
  translate: -50% -50%;
  left: 0;
  top: 0;
}
<div id="pointer"></div>

Another nice way is to use JS's style.setProperty() and change the value to CSS vars like:

const elPointer = document.querySelector("#pointer");

addEventListener("mousemove", (evt) => {
  elPointer.style.setProperty("--x", evt.clientX);
  elPointer.style.setProperty("--y", evt.clientY);
});
body { /* DEMO scrollbars */ min-height: 200vh; }

#pointer {
  position: fixed;
  padding: 20px;
  background: #f0b;
  translate: -50% -50%;
  left: calc(var(--x) * 1px);
  top: calc(var(--y) * 1px);
}
<div id="pointer"></div>
like image 97
Roko C. Buljan Avatar answered Oct 21 '25 17:10

Roko C. Buljan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!