Cursor · 08 of 22
Sticky Cursor
Cursor sticks to element edge
<div class="sticky-area" id="stickyArea">
<div class="sticky-item" id="stickyItem">Stick</div>
<div class="sticky-ring" id="stickyRing"></div>
</div>
.sticky-area {
position: relative;
height: 240px;
display: flex;
align-items: center;
justify-content: center;
background: #12121a;
color: #f0f0f5;
overflow: hidden;
cursor: none;
font-family: sans-serif;
}
.sticky-item {
width: 100px; height: 100px;
background: #333;
display: flex;
align-items: center;
justify-content: center;
border-radius: 12px;
cursor: none;
}
.sticky-ring {
position: absolute;
top: 0; left: 0;
width: 40px; height: 40px;
border: 1px solid rgba(255, 255, 255, 0.5);
border-radius: 50%;
pointer-events: none;
transform: translate(-50%, -50%);
transition: width 0.3s, height 0.3s, border-radius 0.3s, border-color 0.3s;
opacity: 0;
}
var area = document.getElementById('stickyArea');
var item = document.getElementById('stickyItem');
var ring = document.getElementById('stickyRing');
var SMOOTH = 0.1; // ring lerp factor
var mouseX = 0, mouseY = 0; // ring target, relative to area
var ringX = 0, ringY = 0;
var stuck = false;
area.addEventListener('mousemove', function (e) {
if (stuck) return; // while stuck the target is the item's center
var rect = area.getBoundingClientRect();
mouseX = e.clientX - rect.left;
mouseY = e.clientY - rect.top;
});
area.addEventListener('mouseenter', function () { ring.style.opacity = '1'; });
area.addEventListener('mouseleave', function () { ring.style.opacity = '0'; });
item.addEventListener('mouseenter', function () {
stuck = true;
var aRect = area.getBoundingClientRect();
var r = item.getBoundingClientRect();
mouseX = r.left - aRect.left + r.width / 2;
mouseY = r.top - aRect.top + r.height / 2;
ring.style.borderRadius = '12px';
ring.style.width = '100px';
ring.style.height = '100px';
ring.style.borderColor = '#7c5cff';
});
item.addEventListener('mouseleave', function () {
stuck = false;
ring.style.borderRadius = '50%';
ring.style.width = '40px';
ring.style.height = '40px';
ring.style.borderColor = 'rgba(255,255,255,0.5)';
});
function tick() {
ringX += (mouseX - ringX) * SMOOTH;
ringY += (mouseY - ringY) * SMOOTH;
ring.style.left = ringX + 'px';
ring.style.top = ringY + 'px';
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);