How to Create an Image Magnifier Glass Using CSS and JavaScript

You may want to enhance the user experience on your website by providing a zoomed-in view of a product image.

One way to achieve this is by using an image magnifier glass.

In this tutorial, we will explain how to create an image magnifier glass using CSS and JavaScript.


HTML Structure

The first step is to create the HTML structure for the image and the magnifier glass.

The image should be wrapped in a container element and have a unique ID. This ID will be used to reference the image in the JavaScript code.

<div class="img-container">
  <img src="image.jpg" id="img">
</div>

CSS Styles

Next, we need to style the image and the magnifier glass.

The image should have a width and height, and the container element should have a relative position to allow the magnifier glass to be positioned absolute.

.img-container {
position: relative;
width: 500px;
height: 300px;
}

img {

width: 100%;
height: 100%;
}

The magnifier glass can be created using the ::before pseudo-element and positioned absolute in the top left corner of the container element.

The width and height of the magnifier glass should be smaller than the container element and the background should be set to transparent.

.img-container::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100px;
height: 100px;
background: transparent;
}

JavaScript Functionality

Finally, we will add the JavaScript code to create the magnifying effect.

We will use the mousemove event to update the position of the magnifier glass based on the mouse position over the image.

The code should also update the background position of the magnifier glass to show a zoomed-in view of the image.

const img = document.getElementById("img");
const magnifier = document.querySelector(".img-container::before");

img.addEventListener("mousemove", function (e) {
magnifier.style.left = e.pageX - 50 + "px";
magnifier.style.top = e.pageY - 50 + "px";
magnifier.style.backgroundPosition = -${(e.pageX - 50) * 2}px -${(e.pageY - 50) * 2}px;
});

Conclusion

With a few lines of HTML, CSS, and JavaScript, we can create an image magnifier glass to enhance the user experience on our website.

Feel free to adjust the code to fit your needs and play around with the styles to create the perfect image magnifier glass for your project.