How to create a circle that follows the cursor using javascript and css

Create a circle that follows the cursor with javascript and css.

In some dark theme modes, a large cursor really helps identify the different elements on a page.

You can also highlight an element with a different color when the cursor is over it, which you can do with a regular cursor too. The end goal is to enlarge the cursor area.

Let's go

HTML

<div class='cursor' id="cursor"></div>

CSS

Pay attention to the mix-blend-mode property. Its value is set to difference, which works well for both dark and light modes.

.cursor {
  position: fixed;
  border-radius: 50%;
  transform: translateX(-50%) translateY(-50%);
  pointer-events: none;
  left: -100px;
  top: 50%;
  mix-blend-mode: difference;
  background-color: white;
  z-index: 10000;
  border: 2px solid white;
  height: 30px;
  width: 30px;
  transition: all 300ms ease-out;
}

Javascript

Now let's add an event listener on the body itself, which will keep track of the cursor position and adjust the position of the circle accordingly.

var cursor = document.getElementById("cursor");
document.body.addEventListener("mousemove", function(e) {
  cursor.style.left = e.clientX + "px",
    cursor.style.top = e.clientY + "px";
});

Have a web project in mind?

Website design, e-commerce or SEO: our web agency in Paris, Besançon and Normandy can help.

Free quote

Related articles