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`;
})
position: fixed;
. clientX/Y
is relative to the viewport, so is CSS position fixed
.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With