I am trying to add a custom object following the mouse, I want to do that by changing the translate property and assigning x and y values to it. Everything is working fine, when the page is loaded the object is showing up when it is in the first frame and moving throughout the first frame, but when I scroll down, the transform property changed, but the custom object is not showing up, its lost somewhere, but when I scroll back to the top it suddenly appears as its only acting to when the page it on the top most
I am using position fixed because I want the cursor to stay where it is when the page is scrolling and when the scrolling stopes / the mouse started to move, I want to make the object start from there
document.addEventListener("mousemove", e => {
document.querySelector('.mover').style.transform = `translate(${event.pageX}px, ${event.pageY}px)`
});
.mover {
width: 50px;
height: 50px;
position: fixed;
left: -8px;
top: -6px;
transition-duration: .15s;
transition-timing-function: ease-out;
}
html {
cursor: none;
}
body {
background: #F5F9FF;
height: 3000px;
}
<div class="mover">
<svg width="24" height="24" viewBox="0 0 24 24">
<path d="M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12 ,2Z"></path>
</svg>
</div>
3
Answers
The issue you’re facing is related to the
position: fixed
property applied to the.mover
element. When you scroll down the page, the fixed element stays in the same position relative to the viewport, which causes it to appear fixed in the initial viewport area but not in the subsequent scrolled area.To fix this, you can use
position: absolute
instead ofposition: fixed
. By doing so, the element will stay within its containing element and move along with the scrolling content. Here’s an updated version of your code:With this change, the
.mover
element will move along with the mouse cursor regardless of scrolling.Use
client
instead ofpage
You can use the scrollTop property to get the position of the scroll bar and correct the position of the element.
Note that depending on the browser the scrolled element can be
body
orhtml
so it’s safe to check:which of those two is chaning: