I've tried to create a custom cursor for mobile devices, but when the page is scrollable, the custom cursor doesn't follow your finger properly or it drops frames.
Has anyone succeeded in creating a custom cursor for mobile devices that follows your finger while touching the screen using JS?
I have a simple example of code to create a cursor:
// Cursor logic
const cursor = document.getElementById('cursor');
let isTouching = false;
const updateCursorPosition = (x, y) => {
// translate3d + position
cursor.style.transform = `translate3d(${x}px, ${y}px, 0)`;
};
document.addEventListener('touchstart', (e) => {
isTouching = true;
const touch = e.touches[0];
updateCursorPosition(touch.clientX, touch.clientY);
cursor.style.opacity = '1';
}, { passive: true });
document.addEventListener('touchmove', (e) => {
if (!isTouching) return;
const touch = e.touches[0];
updateCursorPosition(touch.clientX, touch.clientY);
}, { passive: true });
document.addEventListener('touchend', () => {
isTouching = false;
cursor.style.opacity = '0';
});
I've noticed this happens more frequently in browsers like Chrome, but not in Firefox. Is there any way to work around this for Chrome or other browsers where this occurs?
body{overflow:hidden}to disable scrolling andscrollBy(x,y)still works, so you could get the touches' distances and do stuff with them. Also, I recommend you useposition:fixedfor the cursor element, that way you don't have to getwindow.scrollXandwindow.scrollYevery time