How and why I added a circle following my mouse pointer

I’ve seen this behaviour on several Russian sites and it looked really slick, especially when the movement was delayed compared to the mouse speed.

Implementing it is really easy using JavaScript and it does not slow down the page rendering or loading.

First of all, I added an empty element in the footer:

<div id="mouse-circle"></div>

And I have styled it:

/**
 * Radial cursor
 */
#mouse-circle {
    position: absolute;
    width: 64px;
    height: 64px;
    margin: -32px 0 0 -32px;
    border: 1px solid #0f1c64;
    border-radius: 50%;
    pointer-events: none;
}

If I wanted to avoid the CSS style, I would have opted for an SVG element. The amount of code would have been smaller.

Next, is the actual mouse follow behaviour, easily coded as below. Note I have used the requestAnimationFrame() function in order to give it a smooth, non-jerky effect.

document.addEventListener('DOMContentLoaded', () => {
    let mousePosX = 0,
        mousePosY = 0,
        mouseCircle = document.getElementById('mouse-circle');

    document.onmousemove = (e) => {
        mousePosX = e.pageX;
        mousePosY = e.pageY;
    }

    let delay = 6,
        revisedMousePosX = 0,
        revisedMousePosY = 0;

    function delayMouseFollow() {
        requestAnimationFrame(delayMouseFollow);

        revisedMousePosX += (mousePosX - revisedMousePosX) / delay;
        revisedMousePosY += (mousePosY - revisedMousePosY) / delay; 

        mouseCircle.style.top = revisedMousePosY + 'px';
        mouseCircle.style.left = revisedMousePosX + 'px';
    }
    delayMouseFollow();
});

You can see this mouse follow behaviour live on Codepen.

Possible Improvements

  • No CSS, just a basic SVG circle shape
  • No HTML, just a dynamic JavaScript node creation
  • Increased delay (12) for an even smoother effect
  • Fade out after mouse stops and fade in on mouse move – this is my favourite 😊
  • A second, transparent circle

And here’s a bonus, it marginally increases time on page, from an SEO point of view, as users tend to move the mouse around, just to see what it looks like.

πŸ‘‹ Added by Ciprian on Thursday, August 27, 2020 in Blog. Last modified on Thursday, November 12, 2020.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy