DEV Community

Gabriel Lazcano
Gabriel Lazcano

Posted on

Create a custom cursor that follows you and inverts colors

Link to original article with examples (recommended): https://gabriellazcano.com/blog/create-a-custom-cursor-that-follows-you-and-inverts-colors/

To achieve this we are using the mix-blend-mode CSS property with the value difference which basically inverts the color of the content it has below it.

.container { 
    width: 100vw; 
    height: 100vh; 
    background-color: white; 
    position: relative; 
}

.circle {
    position: absolute;
    left: 0;
    top: 0;
    width: 60px;
    height: 60px;
    background: white;
    border-radius: 50%;
    pointer-events: none;
    mix-blend-mode: difference;
}
Enter fullscreen mode Exit fullscreen mode

Here we are positioning the circle absolute to the container, giving it a size and with border-radius we are making the div a circle. I disable the pointer-events or we are not going to be able to select any text or really doing anything on the site, we would always be clicking on the cursor div.

Setting the background-color to white in both the .container and the .circle is needed for this to work. In this tutorial I’m just going to use white but it can be done with any color. It just gets the inverted colors and then css just gets the difference.

And we start to see that it blends already. We just have to make the circle to move.

const cursor = document.querySelector(".circle")

function getDimensions(e) {
  cursor.style.top = `${e.clientY - 25}px` // -25px for the size of the circle
  cursor.style.left = `${e.clientX - 25}px`
}

window.addEventListener("mousemove", (e) => {
  getDimensions(e)
});
Enter fullscreen mode Exit fullscreen mode

And it’s working

Bonus: MouseMove Optimization

While it’s working, if you add a debug getDimensions function you might see that there are lots of calls to the function. And this could impact performance.

There is a really known way of solving this problem. By throttling the function calls only firing it once the mousemove event idle for time, in this example 250ms.

const delay = 250

// ...

function throttle(callback, limit) {
  let wait = false
  return function () {
    if (!wait) {
      callback.apply(null, arguments)
      wait = true
      setTimeout(function () {
        wait = false
      }, limit)
    }
  }
}

window.addEventListener("mousemove", (e) => {
  throttle(getDimensions(e), delay)
});
Enter fullscreen mode Exit fullscreen mode

You can get the complete implementation in this link

Related Posts

How to auto adjust font-size to fit div

Top comments (0)