Target Cursor
Custom cursor with a spinning reticle whose four corners snap onto any hovered target element.
pnpm dlx shadcn@latest add @leo/target-cursorProps
| Name | Type | Default | Description |
|---|---|---|---|
| className | string | undefined | - | |
| containerRef | RefObject<HTMLElement | null> | null | undefined | - | Scopes the effect to one element: the cursor is rendered inside it (the element becomes `position: relative` if it is static), only reacts to the pointer over it, and `hideDefaultCursor` applies to it alone. Omitted: the cursor covers the page. |
| cursorColor | string | undefined | #ffffff | |
| cursorColorOnTarget | string | undefined | - | |
| hideDefaultCursor | boolean | undefined | true | Hides the system cursor: on `containerRef` when given, on the whole page otherwise. |
| hoverDuration | number | undefined | 0.2 | |
| initialTarget | string | undefined | - | Selector of an element that the cursor locks onto at mount, before the pointer has moved, so the effect is visible at rest. The first real pointer move releases it. |
| parallaxOn | boolean | undefined | true | |
| spinDuration | number | undefined | 2 | |
| targetSelector | string | undefined | .cursor-target |
Dependencies
- gsap@^3.13.0
Source
"use client";
import { gsap } from "gsap";
import React, { type RefObject, useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { cn } from "@/lib/utils";
// A position: fixed element is positioned relative to the viewport UNLESS an
// ancestor establishes a containing block (transform, perspective, filter,
// will-change of those, or contain). When that happens, the cursor's translate
// no longer maps to viewport coordinates, so we measure and compensate for it.
const getContainingBlock = (element: HTMLElement | null): HTMLElement | null => {
let node = element?.parentElement ?? null;
while (node && node !== document.documentElement) {
const style = getComputedStyle(node);
if (
style.transform !== "none" ||
style.perspective !== "none" ||
style.filter !== "none" ||
style.willChange.includes("transform") ||
style.willChange.includes("perspective") ||
style.willChange.includes("filter") ||
/paint|layout|strict|content/.test(style.contain)
) {
return node;
}
node = node.parentElement;
}
return null;
};
const getContainingBlockOffset = (block: HTMLElement | null): { x: number; y: number } => {
if (!block) return { x: 0, y: 0 };
const rect = block.getBoundingClientRect();
return { x: rect.left + block.clientLeft, y: rect.top + block.clientTop };
};
const BORDER_WIDTH = 3;
const CORNER_SIZE = 12;
const isMobileDevice = (): boolean => {
const hasTouchScreen = "ontouchstart" in window || navigator.maxTouchPoints > 0;
const isSmallScreen = window.innerWidth <= 768;
const userAgent = navigator.userAgent || navigator.vendor || "";
const mobileRegex = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;
return (hasTouchScreen && isSmallScreen) || mobileRegex.test(userAgent.toLowerCase());
};
export interface TargetCursorProps {
targetSelector?: string;
spinDuration?: number;
/** Hides the system cursor: on `containerRef` when given, on the whole page otherwise. */
hideDefaultCursor?: boolean;
hoverDuration?: number;
parallaxOn?: boolean;
cursorColor?: string;
cursorColorOnTarget?: string;
/**
* Scopes the effect to one element: the cursor is rendered inside it (the element
* becomes `position: relative` if it is static), only reacts to the pointer over it,
* and `hideDefaultCursor` applies to it alone. Omitted: the cursor covers the page.
*/
containerRef?: RefObject<HTMLElement | null> | null;
/**
* Selector of an element that the cursor locks onto at mount, before the pointer has
* moved, so the effect is visible at rest. The first real pointer move releases it.
*/
initialTarget?: string;
className?: string;
}
const TargetCursor: React.FC<TargetCursorProps> = ({
targetSelector = ".cursor-target",
spinDuration = 2,
hideDefaultCursor = true,
hoverDuration = 0.2,
parallaxOn = true,
cursorColor = "#ffffff",
cursorColorOnTarget,
containerRef = null,
initialTarget,
className,
}) => {
const cursorRef = useRef<HTMLDivElement>(null);
const cornersRef = useRef<NodeListOf<HTMLDivElement> | null>(null);
const spinTl = useRef<gsap.core.Timeline | null>(null);
const dotRef = useRef<HTMLDivElement>(null);
const containingBlockRef = useRef<HTMLElement | null>(null);
const targetCornerPositionsRef = useRef<{ x: number; y: number }[] | null>(null);
const activeStrengthRef = useRef({ current: 0 });
// Where the cursor is portalled to; resolved after mount so nothing touches the DOM during render.
const [host, setHost] = useState<HTMLElement | null>(null);
const scoped = containerRef !== null;
useEffect(() => {
if (isMobileDevice()) return;
setHost(containerRef?.current ?? document.body);
}, [containerRef]);
const moveCursor = useCallback((x: number, y: number) => {
if (!cursorRef.current) return;
const { x: offsetX, y: offsetY } = getContainingBlockOffset(containingBlockRef.current);
gsap.to(cursorRef.current, {
x: x - offsetX,
y: y - offsetY,
duration: 0.1,
ease: "power3.out",
});
}, []);
useEffect(() => {
if (!host || !cursorRef.current) return;
const container = scoped ? host : null;
const scope: EventTarget = container ?? window;
const cursorTarget: HTMLElement = container ?? document.body;
const originalCursor = cursorTarget.style.cursor;
if (hideDefaultCursor) {
cursorTarget.style.cursor = "none";
}
const originalPosition = container?.style.position ?? "";
if (container && getComputedStyle(container).position === "static") {
container.style.position = "relative";
}
const cursor = cursorRef.current;
const dot = dotRef.current;
cornersRef.current = cursor.querySelectorAll<HTMLDivElement>(".target-cursor-corner");
containingBlockRef.current = container ?? getContainingBlock(cursor);
const getOffset = () => getContainingBlockOffset(containingBlockRef.current);
let activeTarget: Element | null = null;
let currentLeaveHandler: (() => void) | null = null;
let resumeTimeout: ReturnType<typeof setTimeout> | null = null;
let restingOnInitialTarget = false;
const cleanupTarget = (target: Element) => {
if (currentLeaveHandler) {
target.removeEventListener("mouseleave", currentLeaveHandler);
}
currentLeaveHandler = null;
};
const initialOffset = getOffset();
const scopeRect = container?.getBoundingClientRect();
gsap.set(cursor, {
xPercent: -50,
yPercent: -50,
x:
(scopeRect ? scopeRect.left + scopeRect.width / 2 : window.innerWidth / 2) -
initialOffset.x,
y:
(scopeRect ? scopeRect.top + scopeRect.height / 2 : window.innerHeight / 2) -
initialOffset.y,
});
spinTl.current?.kill();
spinTl.current = gsap
.timeline({ repeat: -1 })
.to(cursor, { rotation: "+=360", duration: spinDuration, ease: "none" });
const tickerFn = () => {
const positions = targetCornerPositionsRef.current;
if (!positions || !cursorRef.current || !cornersRef.current) {
return;
}
const strength = activeStrengthRef.current.current;
if (strength === 0) return;
const cursorX = gsap.getProperty(cursorRef.current, "x") as number;
const cursorY = gsap.getProperty(cursorRef.current, "y") as number;
const corners = Array.from(cornersRef.current);
corners.forEach((corner, i) => {
const currentX = gsap.getProperty(corner, "x") as number;
const currentY = gsap.getProperty(corner, "y") as number;
const targetX = positions[i].x - cursorX;
const targetY = positions[i].y - cursorY;
const finalX = currentX + (targetX - currentX) * strength;
const finalY = currentY + (targetY - currentY) * strength;
const duration = strength >= 0.99 ? (parallaxOn ? 0.2 : 0) : 0.05;
gsap.to(corner, {
x: finalX,
y: finalY,
duration: duration,
ease: duration === 0 ? "none" : "power1.out",
overwrite: "auto",
});
});
};
const moveHandler = (e: Event) => {
const { clientX, clientY } = e as MouseEvent;
if (restingOnInitialTarget) {
// The first real pointer move ends the at-rest lock unless the pointer is on that target.
restingOnInitialTarget = false;
const under = document.elementFromPoint(clientX, clientY);
if (activeTarget && !(under && activeTarget.contains(under))) {
currentLeaveHandler?.();
}
}
moveCursor(clientX, clientY);
};
scope.addEventListener("mousemove", moveHandler);
const scrollHandler = () => {
if (!activeTarget || !cursorRef.current || restingOnInitialTarget) return;
const { x: offsetX, y: offsetY } = getOffset();
const mouseX = (gsap.getProperty(cursorRef.current, "x") as number) + offsetX;
const mouseY = (gsap.getProperty(cursorRef.current, "y") as number) + offsetY;
const elementUnderMouse = document.elementFromPoint(mouseX, mouseY);
const isStillOverTarget =
elementUnderMouse &&
(elementUnderMouse === activeTarget ||
elementUnderMouse.closest(targetSelector) === activeTarget);
if (!isStillOverTarget) {
currentLeaveHandler?.();
}
};
window.addEventListener("scroll", scrollHandler, { passive: true });
const mouseDownHandler = () => {
if (!dotRef.current) return;
gsap.to(dotRef.current, { scale: 0.7, duration: 0.3 });
gsap.to(cursorRef.current, { scale: 0.9, duration: 0.2 });
};
const mouseUpHandler = () => {
if (!dotRef.current) return;
gsap.to(dotRef.current, { scale: 1, duration: 0.3 });
gsap.to(cursorRef.current, { scale: 1, duration: 0.2 });
};
scope.addEventListener("mousedown", mouseDownHandler);
window.addEventListener("mouseup", mouseUpHandler);
// A scoped cursor must not linger where the pointer left its container.
const showCursor = () => {
gsap.to(cursor, { autoAlpha: 1, duration: 0.15 });
};
const hideCursor = () => {
gsap.to(cursor, { autoAlpha: 0, duration: 0.15 });
};
if (container) {
container.addEventListener("mouseenter", showCursor);
container.addEventListener("mouseleave", hideCursor);
}
const engage = (target: Element) => {
if (!cursorRef.current || !cornersRef.current) return;
if (activeTarget === target) return;
if (activeTarget) {
cleanupTarget(activeTarget);
}
if (resumeTimeout) {
clearTimeout(resumeTimeout);
resumeTimeout = null;
}
activeTarget = target;
const corners = Array.from(cornersRef.current);
for (const corner of corners) gsap.killTweensOf(corner, "x,y");
gsap.killTweensOf(cursorRef.current, "rotation");
spinTl.current?.pause();
gsap.set(cursorRef.current, { rotation: 0 });
if (cursorColorOnTarget) {
gsap.to(corners, {
borderColor: cursorColorOnTarget,
duration: 0.15,
ease: "power2.out",
});
if (dotRef.current) {
gsap.to(dotRef.current, {
backgroundColor: cursorColorOnTarget,
duration: 0.15,
ease: "power2.out",
});
}
}
const rect = target.getBoundingClientRect();
const { x: offsetX, y: offsetY } = getOffset();
const cursorX = gsap.getProperty(cursorRef.current, "x") as number;
const cursorY = gsap.getProperty(cursorRef.current, "y") as number;
const positions = [
{ x: rect.left - BORDER_WIDTH - offsetX, y: rect.top - BORDER_WIDTH - offsetY },
{
x: rect.right + BORDER_WIDTH - CORNER_SIZE - offsetX,
y: rect.top - BORDER_WIDTH - offsetY,
},
{
x: rect.right + BORDER_WIDTH - CORNER_SIZE - offsetX,
y: rect.bottom + BORDER_WIDTH - CORNER_SIZE - offsetY,
},
{
x: rect.left - BORDER_WIDTH - offsetX,
y: rect.bottom + BORDER_WIDTH - CORNER_SIZE - offsetY,
},
];
targetCornerPositionsRef.current = positions;
gsap.ticker.add(tickerFn);
gsap.to(activeStrengthRef.current, {
current: 1,
duration: hoverDuration,
ease: "power2.out",
});
corners.forEach((corner, i) => {
gsap.to(corner, {
x: positions[i].x - cursorX,
y: positions[i].y - cursorY,
duration: 0.2,
ease: "power2.out",
});
});
const leaveHandler = () => {
gsap.ticker.remove(tickerFn);
targetCornerPositionsRef.current = null;
gsap.set(activeStrengthRef.current, { current: 0, overwrite: true });
activeTarget = null;
if (cursorColorOnTarget && cornersRef.current) {
gsap.to(Array.from(cornersRef.current), {
borderColor: cursorColor,
duration: 0.15,
ease: "power2.out",
});
if (dotRef.current) {
gsap.to(dotRef.current, {
backgroundColor: cursorColor,
duration: 0.15,
ease: "power2.out",
});
}
}
if (cornersRef.current) {
const leaving = Array.from(cornersRef.current);
gsap.killTweensOf(leaving, "x,y");
const restPositions = [
{ x: -CORNER_SIZE * 1.5, y: -CORNER_SIZE * 1.5 },
{ x: CORNER_SIZE * 0.5, y: -CORNER_SIZE * 1.5 },
{ x: CORNER_SIZE * 0.5, y: CORNER_SIZE * 0.5 },
{ x: -CORNER_SIZE * 1.5, y: CORNER_SIZE * 0.5 },
];
const tl = gsap.timeline();
leaving.forEach((corner, index) => {
tl.to(
corner,
{
x: restPositions[index].x,
y: restPositions[index].y,
duration: 0.3,
ease: "power3.out",
},
0,
);
});
}
resumeTimeout = setTimeout(() => {
if (!activeTarget && cursorRef.current && spinTl.current) {
const currentRotation = gsap.getProperty(cursorRef.current, "rotation") as number;
const normalizedRotation = currentRotation % 360;
spinTl.current.kill();
spinTl.current = gsap
.timeline({ repeat: -1 })
.to(cursorRef.current, { rotation: "+=360", duration: spinDuration, ease: "none" });
gsap.to(cursorRef.current, {
rotation: normalizedRotation + 360,
duration: spinDuration * (1 - normalizedRotation / 360),
ease: "none",
onComplete: () => {
spinTl.current?.restart();
},
});
}
resumeTimeout = null;
}, 50);
cleanupTarget(target);
};
currentLeaveHandler = leaveHandler;
target.addEventListener("mouseleave", leaveHandler);
};
const enterHandler = (e: Event) => {
let current: Element | null = e.target as Element;
while (current && current !== document.body) {
if (current.matches(targetSelector)) {
engage(current);
return;
}
current = current.parentElement;
}
};
scope.addEventListener("mouseover", enterHandler);
const first = initialTarget ? (container ?? document).querySelector(initialTarget) : null;
const restOnInitialTarget = () => {
if (!first) return;
const rect = first.getBoundingClientRect();
const { x: offsetX, y: offsetY } = getOffset();
gsap.set(cursor, {
x: rect.left + rect.width / 2 - offsetX,
y: rect.top + rect.height / 2 - offsetY,
});
restingOnInitialTarget = true;
if (activeTarget === first) {
// engage() ignores the current target, so drop it first to recompute the corner positions.
cleanupTarget(first);
activeTarget = null;
}
engage(first);
};
restOnInitialTarget();
// Web fonts and layout shifts move the target after mount; re-measure while still resting on it.
let disposed = false;
let relockFrame = 0;
const relock = () => {
if (disposed || !restingOnInitialTarget) return;
restOnInitialTarget();
};
if (first) {
(document.fonts?.ready ?? Promise.resolve())
.catch(() => undefined)
.then(() => {
if (!disposed) relockFrame = requestAnimationFrame(relock);
});
}
const resizeHandler = () => {
if (!container) containingBlockRef.current = getContainingBlock(cursor);
relock();
};
window.addEventListener("resize", resizeHandler);
return () => {
disposed = true;
cancelAnimationFrame(relockFrame);
gsap.ticker.remove(tickerFn);
scope.removeEventListener("mousemove", moveHandler);
scope.removeEventListener("mouseover", enterHandler);
scope.removeEventListener("mousedown", mouseDownHandler);
window.removeEventListener("mouseup", mouseUpHandler);
window.removeEventListener("scroll", scrollHandler);
window.removeEventListener("resize", resizeHandler);
if (container) {
container.removeEventListener("mouseenter", showCursor);
container.removeEventListener("mouseleave", hideCursor);
container.style.position = originalPosition;
}
if (activeTarget) {
cleanupTarget(activeTarget);
}
if (resumeTimeout) clearTimeout(resumeTimeout);
spinTl.current?.kill();
gsap.killTweensOf([cursor, dot, activeStrengthRef.current]);
if (cornersRef.current) gsap.killTweensOf(Array.from(cornersRef.current));
cursorTarget.style.cursor = originalCursor;
targetCornerPositionsRef.current = null;
activeStrengthRef.current.current = 0;
};
}, [
host,
scoped,
targetSelector,
spinDuration,
moveCursor,
hideDefaultCursor,
hoverDuration,
parallaxOn,
cursorColor,
cursorColorOnTarget,
initialTarget,
]);
if (!host) {
return null;
}
return createPortal(
<div
ref={cursorRef}
aria-hidden="true"
className={cn(
scoped ? "absolute" : "fixed",
"top-0 left-0 w-0 h-0 pointer-events-none z-[2147483647]",
className,
)}
style={{ willChange: "transform" }}
>
<div
ref={dotRef}
className="absolute top-1/2 left-1/2 w-1 h-1 rounded-full -translate-x-1/2 -translate-y-1/2"
style={{ willChange: "transform", backgroundColor: cursorColor }}
/>
<div
className="target-cursor-corner absolute top-1/2 left-1/2 w-3 h-3 border-[3px] -translate-x-[150%] -translate-y-[150%] border-r-0 border-b-0"
style={{ willChange: "transform", borderColor: cursorColor }}
/>
<div
className="target-cursor-corner absolute top-1/2 left-1/2 w-3 h-3 border-[3px] translate-x-1/2 -translate-y-[150%] border-l-0 border-b-0"
style={{ willChange: "transform", borderColor: cursorColor }}
/>
<div
className="target-cursor-corner absolute top-1/2 left-1/2 w-3 h-3 border-[3px] translate-x-1/2 translate-y-1/2 border-l-0 border-t-0"
style={{ willChange: "transform", borderColor: cursorColor }}
/>
<div
className="target-cursor-corner absolute top-1/2 left-1/2 w-3 h-3 border-[3px] -translate-x-[150%] translate-y-1/2 border-r-0 border-t-0"
style={{ willChange: "transform", borderColor: cursorColor }}
/>
</div>,
host,
);
};
export { TargetCursor };
export default TargetCursor;