Typography · 05 of 33
Magnetic Letters
Move cursor near letters — they'll magnetically attract
<p class="magnetic-headline">
<span class="mag-char">M</span><span class="mag-char">a</span><span class="mag-char">g</span><span class="mag-char">n</span><span class="mag-char">e</span><span class="mag-char">t</span><span class="mag-char">i</span><span class="mag-char">c</span>
</p>
.magnetic-headline {
display: flex;
justify-content: center;
font-size: 3.5rem;
font-weight: 600;
}
.mag-char {
display: inline-block;
will-change: transform;
}
var chars = document.querySelectorAll('.mag-char');
var RADIUS = 120; // px — attraction range
var STRENGTH = 0.35;
var SMOOTH = 0.12; // lerp factor
var mouseX = -9999, mouseY = -9999;
var targets = [], current = [];
chars.forEach(function () {
targets.push({ x: 0, y: 0 });
current.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 = mouseX - (r.left + r.width / 2);
var dy = mouseY - (r.top + r.height / 2);
var dist = Math.sqrt(dx * dx + dy * dy);
if (dist < RADIUS && dist > 0) {
var f = (1 - dist / RADIUS) * STRENGTH;
targets[i].x = (dx / dist) * f * 30;
targets[i].y = (dy / dist) * f * 30;
} else {
targets[i].x *= 0.9;
targets[i].y *= 0.9;
}
current[i].x += (targets[i].x - current[i].x) * SMOOTH;
current[i].y += (targets[i].y - current[i].y) * SMOOTH;
el.style.transform = 'translate(' + current[i].x + 'px, ' + current[i].y + 'px)';
});
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);