Reputation: 4033
I'm currently trying to implement some custom cursor - a div that moves with the cursor. To do so, I use the following code:
document.addEventListener('mousemove', this.handleMouseMove);
handleMouseMove = (event) => {
const y = event.pageY;
const x = event.pageX;
const ref = document.querySelector('.follow-cursor');
ref.style.left = x + 'px';
ref.style.top = y + 'px';
};
It works fine, but there's one more problem: scrolling. So far, the div is not moving on scroll and hence not following the cursor on scroll. How can I change that? Reference: this website.
Upvotes: 2
Views: 3147
Reputation: 81
Yeah NickSlash's answer works fine. You can try both. Just in this case do not forget to add the id in the html
const cursor = document.getElementById("cursor")
const moveCursor = (event) => {
const y = event.pageY
const x = event.pageX
const scrollLeft =
window.pageXOffset !== undefined
? window.pageXOffset
: (document.documentElement || document.body.parentNode || document.body)
.scrollLeft
onst scrollTop =
window.pageYOffset !== undefined
? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body)
.scrollTop
cursor.style.left = x - scrollLeft + "px"
cursor.style.top = y - scrollTop + "px"`}`
document.addEventListener("mousemove", moveCursor)
Upvotes: 0
Reputation: 5077
I don't think this is how the site you linked to does this, but it works.
handleMouseMove = (event) => {
const y = event.pageY;
const x = event.pageX;
const ref = document.querySelector('.follow-cursor')
const scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
const scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
ref.style.left = x - scrollLeft + 'px';
ref.style.top = y - scrollTop + 'px';
};
If you apply style position: fixed
to your .follow-cursor it should work.
example: https://jsfiddle.net/bf5wy9v3/
Upvotes: 6