Programmer's Picnic

Amazon-Style Image Magnifier — Lesson, Code & Live Demo

Light saffron template • clean cards • copy-paste friendly • Blogger safe

Lesson — How the Amazon-Style Magnifier Works

The magnifier uses three simple pieces:

  1. Small image — the image users see on the page.
  2. Lens — a floating circle over the image showing a zoomed portion via background-image.
  3. Result box — a bigger box that shows the magnified area by syncing background-position.

Key steps the script does:


🔍 Live Demo

Demo Image
Tip: keep your source image high-resolution for crisp zoom.

💻 Full Code — Copy & Paste

Copy the block below into a new HTML file or into Blogger’s HTML view.

<!-- Amazon-style magnifier (Light Saffron Template) -->

<div class="magnify-wrapper">
  <div class="magnify-container" id="demoContainer">
    <img id="demoImg" class="magnify-small"
      src="https://blogger.googleusercontent.com/img/a/AVvXsEhlfwIqq3YYxj6LMFr4E7IKN2bYIor-bFpbUXBT3Jthp8PKmRdWozV3hEk2xcj3kPrJ9WBIkXCr4lw5MTAz0AE5b0lPhQ2ReNbCmMOumP4zLTEOb7GY6s4YWcgcCfzltJVmQcgCObeQNRvn_SWPa_2c6cROZUOBHhRJB20PaV-peuA3GTSafM8JxgaYu5M=s257"
      alt="Demo Image">
    <div id="demoLens" class="magnify-lens"></div>
  </div>

  <div id="demoResult" class="magnify-result"></div>
</div>

<script>
(function(){
  const img = document.getElementById("demoImg");
  const lens = document.getElementById("demoLens");
  const result = document.getElementById("demoResult");
  const container = document.getElementById("demoContainer");

  const zoom = 3;

  function init() {
    lens.style.backgroundImage = `url(${img.src})`;
    result.style.backgroundImage = `url(${img.src})`;

    container.addEventListener("mouseenter", () => {
      lens.style.display = "block";
      result.style.display = "block";
    });

    container.addEventListener("mouseleave", () => {
      lens.style.display = "none";
      result.style.display = "none";
    });

    container.addEventListener("mousemove", moveLens);
    container.addEventListener("pointermove", moveLens);
  }

  function moveLens(e) {
    const rect = img.getBoundingClientRect();
    if (!rect.width || !rect.height) return;

    let x = e.clientX - rect.left - lens.offsetWidth / 2;
    let y = e.clientY - rect.top - lens.offsetHeight / 2;

    if (x < 0) x = 0;
    if (y < 0) y = 0;
    if (x > img.width - lens.offsetWidth) x = img.width - lens.offsetWidth;
    if (y > img.height - lens.offsetHeight) y = img.height - lens.offsetHeight;

    lens.style.left = x + "px";
    lens.style.top = y + "px";

    const bgW = img.width * zoom;
    const bgH = img.height * zoom;

    lens.style.backgroundSize = `${bgW}px ${bgH}px`;
    result.style.backgroundSize = `${bgW}px ${bgH}px`;

    lens.style.backgroundPosition = `-${x * zoom}px -${y * zoom}px`;
    result.style.backgroundPosition = `-${x * zoom}px -${y * zoom}px`;
  }

  if (img.complete) init();
  else img.addEventListener("load", init);
})();
</script>

Extras