1

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?

5
  • 2
    Start by showing us what you got so far, in the form of a minimal reproducible example. Commented Nov 24 at 14:46
  • This sounds like something that could be quite challenging to get smooth as it will be tied to both the touch and the scroll position. Scroll animations alone can be tricky to get smooth. Please can you provide a minimal reproducible example; I'd be interested to see what you have so far. Commented Nov 24 at 15:10
  • Mobile browsers used to pause/throttle animation while scrolling as an optimisation, I imagine this is something similar (though as mentioned, we need more info to be able to help) Commented Nov 24 at 15:50
  • You could take over the controls to scrolling. You can set body{overflow:hidden} to disable scrolling and scrollBy(x,y) still works, so you could get the touches' distances and do stuff with them. Also, I recommend you use position:fixed for the cursor element, that way you don't have to get window.scrollX and window.scrollY every time Commented Nov 24 at 16:27
  • This usually happens in the Chrome browser, perhaps due to some limitation related to the scroll thread priority. Commented Nov 25 at 13:35

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.