Categories
Web development

CSS & JavaScript Image Magnifier Glass

Image Magnifier Glass

Demo:

*to see the Magnifier Glass effect on the website click here.

To create the CSS & JavaScript Image Magnifier Glass follow the steps below:

  1. Add HTML
  2. Add CSS
  3. Add JavaScript

Step1.

Add HTML

Create the image container and add the image that you want to Magnifique:

<div class="image-container">
  <img id="dinant" src="https://lenadesign.org/wp-content/uploads/2021/06/image-mg.jpg" width="600" height="440">
</div>

Step2.

Add CSS

Set the colour and the position of the background and elements:

body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.image-container {
  position:relative;
}

Style the image:

#dinant {
  border: 10px solid #333;
  box-shadow: 0 0 20px rgba(0,0,0,0.6);
}

And add magnifying glass:

.magnifier-glass {
  position: absolute;
  border: 5px solid #333;
  border-radius: 50%;
  cursor: none;
  width: 100px;
  height: 100px;
}

.magnifier-glass:before {
  content:"";
  position: absolute;
  width: 15px;
  height:70px;
  border-radius: 30px;
  background-color: #333;
  top:86px;
  left:90px;
  transform: rotate(-33deg);
}

Step3.

Add JavaScript

function Zoom(img, zoom) {
  var img, loupe, width, height, back;
  img = document.getElementById("dinant");

  loupe = document.createElement("div");
  loupe.setAttribute("class", "magnifier-glass");

  img.parentElement.insertBefore(loupe, img);
  loupe.style.backgroundImage = "url('" + img.src + "')";
  loupe.style.backgroundRepeat = "no-repeat";
  loupe.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px";
  back = 2;
  width = loupe.offsetWidth / 2;
  height = loupe.offsetHeight / 2;

  loupe.addEventListener("mousemove", moveLoupe);
  img.addEventListener("mousemove", moveLoupe);
  loupe.addEventListener("touchmove", moveLoupe);
  img.addEventListener("touchmove", moveLoupe);
  
  function moveLoupe(e) {
    var pos, x, y;

    e.preventDefault();

    pos = position(e);
    x = pos.x;
    y = pos.y;

    if (x > img.width - (width / zoom)) {x = img.width - (width / zoom);}
    if (x < width / zoom) {x = width / zoom;}
    if (y > img.height - (height / zoom)) {y = img.height - (height / zoom);}
    if (y < height / zoom) {y = height / zoom;}

    loupe.style.left = (x - width) + "px";
    loupe.style.top = (y - height) + "px";
    loupe.style.backgroundPosition = "-" + ((x * zoom) - width + back) + "px -" + ((y * zoom) - height + back) + "px";
  }
  function position(e) {
    var a, x = 0, y = 0;
    e = e || window.event;

    a = img.getBoundingClientRect();
    x = e.pageX - a.left;
    y = e.pageY - a.top;

    x = x - window.pageXOffset;
    y = y - window.pageYOffset;
    return {x : x, y : y};
  }
}

Zoom("dinant", 2);

Enjoy coding!

Read also:

CSS/JS Eye Follows Mouse Cursor + Blink on Hover

Div (circle) follows the cursor

CSS Zoom on Hover