Gallery · 10 of 33

Magnetic Cursor

Custom cursor sticks to image

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="magnetic-wrap" id="magneticWrap">
  <img src="https://picsum.photos/id/57/800/600" alt="Castle">
  <div class="magnetic-cursor" id="magneticCursor">View</div>
</div>

CSS

.magnetic-wrap {
  position: relative;
  width: 400px;
  aspect-ratio: 4 / 3;
  overflow: hidden;
  border-radius: 12px;
  cursor: none;
}

.magnetic-wrap img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.magnetic-cursor {
  position: absolute;
  top: 0; left: 0;
  width: 60px; height: 60px;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(4px);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: system-ui, sans-serif;
  font-size: 0.75rem;
  font-weight: 600;
  color: #fff;
  transform: translate(-50%, -50%) scale(0);
  transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1);
  pointer-events: none;
  z-index: 10;
}

JavaScript

var wrap = document.getElementById('magneticWrap');
var cursor = document.getElementById('magneticCursor');

wrap.addEventListener('mousemove', function (e) {
  var rect = wrap.getBoundingClientRect();
  cursor.style.left = (e.clientX - rect.left) + 'px';
  cursor.style.top = (e.clientY - rect.top) + 'px';
  cursor.style.transform = 'translate(-50%, -50%) scale(1)';
});

wrap.addEventListener('mouseleave', function () {
  cursor.style.transform = 'translate(-50%, -50%) scale(0)';
});