Build a Custom Cursor with CSS and JavaScript

A step-by-step custom cursor: hide the pointer, follow it with transform, and change state over links.


Build a Custom Cursor with CSS and JavaScript


This tutorial builds one cursor, not a gallery. The six-demo collection is cursor effects and animation. After this, the label cursor and blend cursor are small variations of the same loop.

What you are building

A dot that follows the pointer. Over a link or button it scales up. On a touch screen it stays hidden, because a fake cursor covers the thing the finger is trying to hit.

Markup

One element is enough. Put it at the end of body so it paints above the page.

<div class="cursor" id="cursor"></div>
<p><a href="#work">View the work</a></p>

Position it without layout

left and top on every pointermove force layout. transform: translate() does not.

.cursor {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 20;
  width: 16px;
  height: 16px;
  margin: -8px 0 0 -8px;
  border: 2px solid #111;
  border-radius: 50%;
  pointer-events: none;
  transition: transform 0.2s ease;
}
.cursor.is-hot {
  transform: scale(1.8);
  background: #111;
}

The scale has to compose with the translate. Put the translate on the element from JavaScript, and the scale on an inner span, or set one transform string that includes both. The preview uses an inner span so the two transforms do not overwrite each other.

Follow the pointer

const cursor = document.getElementById("cursor");
const finePointer = window.matchMedia("(pointer: fine)").matches;

if (finePointer) {
  document.documentElement.classList.add("custom-cursor");
  window.addEventListener("pointermove", (event) => {
    cursor.style.transform = `translate(${event.clientX}px, ${event.clientY}px)`;
    const hot = event.target.closest("a, button");
    cursor.classList.toggle("is-hot", Boolean(hot));
  }, { passive: true });
}
html.custom-cursor, html.custom-cursor a, html.custom-cursor button { cursor: none; }
html.custom-cursor input, html.custom-cursor textarea { cursor: text; }

Checks before you ship it

The particle trail and stardust trail use the same move listener, then draw on a canvas instead of a div.