By the end of this lesson, you will be able to:
This lesson uses a light saffron theme — calm, readable, and distraction-free.
Before writing code, let’s understand the idea.
background-image
👉 Important insight:
We are not enlarging the image element.
We are enlarging the background image and shifting it.
This is the same trick Amazon uses.
We start with simple HTML.
<div class="magnify-wrapper">
<div class="magnify-container" id="demoContainer">
<img id="demoImg" class="magnify-small"
src="YOUR_IMAGE_URL"
alt="Product Image">
<div id="demoLens" class="magnify-lens"></div>
</div>
<div id="demoResult" class="magnify-result"></div>
</div>
.magnify-container — holds the image and lens (relative positioning).magnify-lens — floats above the image and follows the mouse.magnify-result — shows the zoomed outputThink of it as:
Image → Lens → Preview
Now we add CSS to make it usable and beautiful.
position: absoluteposition: relativebackground-size and background-position
.magnify-container {
position: relative;
width: 300px;
}
.magnify-lens {
position: absolute;
width: 120px;
height: 120px;
border-radius: 50%;
display: none;
background-repeat: no-repeat;
}
.magnify-result {
width: 380px;
height: 380px;
display: none;
background-repeat: no-repeat;
}
border-radius: 50%, the lens becomes square.
const img = document.getElementById("demoImg");
const lens = document.getElementById("demoLens");
const result = document.getElementById("demoResult");
const container = document.getElementById("demoContainer");
const zoom = 3;
zoom = 3 means 3× magnification
function init() {
lens.style.backgroundImage = `url(${img.src})`;
result.style.backgroundImage = `url(${img.src})`;
container.addEventListener("mouseenter", show);
container.addEventListener("mouseleave", hide);
container.addEventListener("mousemove", moveLens);
}
👉 We wait for image load because we need correct width and height for zoom math.
let x = e.clientX - rect.left - lens.offsetWidth / 2; let y = e.clientY - rect.top - lens.offsetHeight / 2;
Meaning:
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;
This prevents the lens from going outside the image.
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`;
✨ Key Insight:
We move the background opposite to the mouse
so the correct area appears magnified.
const zoom = 4;border-radius: 0;This lesson teaches more than a feature.
This is front-end engineering, not decoration.
☕🌿 – Programmer’s Picnic