Cursor · 12 of 22

Zoom Lens

Magnifying glass effect

HTML · CSS · JavaScript · No dependencies · MIT

HTML

<div class="zoom-area" id="zoomArea">
  <img src="https://picsum.photos/id/50/300/200" alt="Zoom">
  <div class="zoom-lens" id="zoomLens"></div>
</div>

CSS

.zoom-area {
  position: relative;
  height: 240px;
  overflow: hidden;
  cursor: none;
}

.zoom-area img {
  width: 100%; height: 100%;
  object-fit: cover;
}

.zoom-lens {
  position: absolute;
  width: 100px; height: 100px;
  border-radius: 50%;
  border: 2px solid #fff;
  /* Same image as the area, blown up to act as the magnified view */
  background-image: url('https://picsum.photos/id/50/300/200');
  background-size: 300% 200%;
  pointer-events: none;
  opacity: 0;
  transform: translate(-50%, -50%) scale(0);
  transition: opacity 0.2s, transform 0.2s;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
}

JavaScript

var area = document.getElementById('zoomArea');
var lens = document.getElementById('zoomLens');

area.addEventListener('mousemove', function (e) {
  var rect = area.getBoundingClientRect();
  var x = e.clientX - rect.left;
  var y = e.clientY - rect.top;
  lens.style.left = x + 'px';
  lens.style.top = y + 'px';

  // Pan the magnified background to the point under the lens
  var bgX = (x / rect.width) * 100;
  var bgY = (y / rect.height) * 100;
  lens.style.backgroundPosition = bgX + '% ' + bgY + '%';
});

area.addEventListener('mouseenter', function () {
  lens.style.opacity = '1';
  lens.style.transform = 'translate(-50%, -50%) scale(1)';
});

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