Typography · 06 of 33
Cursor Repulsion
Letters repel from your cursor
<p class="repel-headline">
<span class="repel-char">R</span><span class="repel-char">e</span><span class="repel-char">p</span><span class="repel-char">e</span><span class="repel-char">l</span><span class="repel-char"> </span><span class="repel-char">M</span><span class="repel-char">e</span>
</p>
.repel-headline {
display: flex;
justify-content: center;
font-size: 3.5rem;
font-weight: 600;
}
.repel-char {
display: inline-block;
will-change: transform;
}
var chars = document.querySelectorAll('.repel-char');
var MAX_DIST = 150; // px — repulsion range
var STRENGTH = 1.2;
var SMOOTH = 0.18;
var mouseX = -9999, mouseY = -9999;
var positions = [];
chars.forEach(function () { positions.push({ x: 0, y: 0 }); });
document.addEventListener('mousemove', function (e) {
mouseX = e.clientX;
mouseY = e.clientY;
});
function tick() {
chars.forEach(function (el, i) {
var r = el.getBoundingClientRect();
var dx = (r.left + r.width / 2) - mouseX;
var dy = (r.top + r.height / 2) - mouseY;
var dist = Math.sqrt(dx * dx + dy * dy) || 1;
if (dist < MAX_DIST) {
var force = (1 - dist / MAX_DIST) * STRENGTH * 80;
positions[i].x += ((dx / dist) * force - positions[i].x) * SMOOTH;
positions[i].y += ((dy / dist) * force - positions[i].y) * SMOOTH;
} else {
positions[i].x *= 0.92;
positions[i].y *= 0.92;
}
el.style.transform = 'translate(' + positions[i].x + 'px, ' + positions[i].y + 'px)';
});
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);