Contextual Label Cursor

A custom cursor that swaps to View, Drag, or Play when it crosses a target, using one element and pointer events.


Contextual Label Cursor


The cursor is a single fixed element. On empty space it is a small dot. Over a target it grows into a pill and reads the label from data-cursor.

Related: cursor effects, blend cursor, particle trail, and the custom cursor tutorial.

HTML

<div class="label-cursor" id="labelCursor" data-label=""></div>
<a href="#work" data-cursor="View">Selected work</a>
<button type="button" data-cursor="Drag">Reorder</button>
<a href="#reel" data-cursor="Play">Showreel</a>

CSS

.label-cursor {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 20;
  width: 14px;
  height: 14px;
  margin: -7px 0 0 -7px;
  border-radius: 999px;
  background: #111;
  color: #fff;
  pointer-events: none;
  display: grid;
  place-items: center;
  font: 600 12px/1 Inter, system-ui, sans-serif;
  letter-spacing: 0.04em;
  transition: width 0.25s ease, height 0.25s ease, margin 0.25s ease, padding 0.25s ease;
}
.label-cursor[data-label]:not([data-label=""]) {
  width: auto;
  height: 36px;
  margin: -18px 0 0 -12px;
  padding: 0 14px;
}
.label-cursor[data-label]:not([data-label=""])::after {
  content: attr(data-label);
}
@media (pointer: coarse) {
  .label-cursor { display: none; }
}

Hide the native cursor on the page when the custom one is active: body { cursor: none; } and restore cursor: auto inside text fields.

JavaScript

Move with transform so the browser can keep the dot on the compositor thread. Read the label from the element under the pointer.

const cursor = document.getElementById("labelCursor");
const fine = window.matchMedia("(pointer: fine)").matches;
if (cursor && fine) {
  document.body.classList.add("has-label-cursor");
  window.addEventListener("pointermove", (event) => {
    cursor.style.transform = `translate(${event.clientX}px, ${event.clientY}px)`;
    const target = event.target.closest("[data-cursor]");
    cursor.dataset.label = target ? target.dataset.cursor : "";
  });
}
body.has-label-cursor,
body.has-label-cursor a,
body.has-label-cursor button {
  cursor: none;
}
body.has-label-cursor input,
body.has-label-cursor textarea {
  cursor: text;
}