X

Headline

This is an important message requiring you to make a choice if you're based in the EU.

How to Create an Image Zoom Using CSS and JavaScript

Image zoom is one of the most useful functionalities that a web page may have. You can create a quite attractive one using CSS and JavaScript. If you’re interested, let’s dive in and do it together, step by step!

1. Create HTML

As always, we need to create an HTML code as a base. Create a <div> element as a container and give a class to it. Then comes the image to which the zoom will later be applied. We insert the image using an HTML <img> tag with its proper attributes.

<div class="img-zoom-container">
  <img id="theimage" src="/uploads/media/default/0001/03/d670346cbbbda5cc6a629e275f87fd53d58ebc51.jpeg" width="300" height="240" alt="House">
  <div id="myresult" class="img-zoom-result"></div>
</div>

2. Add CSS

The important thing here is that the container must have a relative positioning, thus define the CSS position property to its “relative” value. The result can be placed anywhere on the page, but it must have a class named "img-zoom-result".

Both the image and the result must have IDs that will be used when a javaScript initiates the zoom effect.

The border, width and height properties are used to style the little zoom square (lens) on the image and the result container.

Let’s see how the code looks like:

* {box-sizing: border-box;}

.img-zoom-container {
  position: relative;
}

.img-zoom-lens {
  position: absolute;
  border: 1px solid #d4d4d4;
  /*set the size of the lens:*/
  width: 40px;
  height: 40px;
}

.img-zoom-result {
  border: 1px solid #d4d4d4;
  /*set the size of the result div:*/
  width: 300px;
  height: 300px;
}

3. Add JavaScript

See the code below to find out all we need to do by the help of JavaScript.

function imageZoom(imgID, resultID) {
  var img, lens, result, cx, cy;
  img = document.getElementById(imgID);
  result = document.getElementById(resultID);
  /* Create lens: */
  lens = document.createElement("DIV");
  lens.setAttribute("class", "img-zoom-lens");
  /* Insert lens: */
  img.parentElement.insertBefore(lens, img);
  /* Calculate the ratio between the div of the result and the lens: */
  cx = result.offsetWidth / lens.offsetWidth;
  cy = result.offsetHeight / lens.offsetHeight;
  /* Set background properties for the result DIV */
  result.style.backgroundImage = "url('" + img.src + "')";
  result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px";
  /* Execute a function when someone moves the cursor over the image, or over the lens: */
  lens.addEventListener("mousemove", moveLens);
  img.addEventListener("mousemove", moveLens);
  /* The function above for touch screens: */
  lens.addEventListener("touchmove", moveLens);
  img.addEventListener("touchmove", moveLens);
  function moveLens(e) {
    var pos, x, y;
    /* Prevent any other actions that may occur when moving over the image */
	e.preventDefault();
    /* Get the x and y positions of the cursor: */
    pos = getCursorPos(e);
    /* Calculate the position of the lens: */
	x = pos.x - (lens.offsetWidth / 2);
    y = pos.y - (lens.offsetHeight / 2);
    /* Prevent the lens from being positioned outside the image: */
    if (x > img.width - lens.offsetWidth) {x = img.width - lens.offsetWidth;}
    if (x < 0) {x = 0;}
    if (y > img.height - lens.offsetHeight) {y = img.height - lens.offsetHeight;}
    if (y < 0) {y = 0;}
    /* Set the lens position: */
    lens.style.left = x + "px";
	lens.style.top = y + "px";
    /* Display what the lens "sees": */
    result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px";
  }
  function getCursorPos(e) {
    var a, x = 0, y = 0;
	e = e || window.event;
    /* Get the x and y positions of the image: */
	a = img.getBoundingClientRect();
    /* Calculate the cursor's x and y coordinates, relative to the image: */
	x = e.pageX - a.left;
	y = e.pageY - a.top;
    /* Consider any page scrolling: */
	x = x - window.pageXOffset;
	y = y - window.pageYOffset;
    return {x : x, y : y};
  }
}

The last thing to do is initiating the zoom effect, that is done like this:

<script>
imageZoom("myimage", "myresult"); 
</script>

Now let’s bring all the parts together and try what we’ve created!

Example

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
      * {box-sizing: border-box;}
      .img-zoom-container {
      position: relative;
      }
      .img-zoom-lens {
      position: absolute;
      border: 1px solid #d4d4d4;
      /*set the size of the lens:*/
      width: 40px;
      height: 40px;
      }
      .img-zoom-result {
      border: 1px solid #d4d4d4;
      /*set the size of the result div:*/
      width: 150px;
      height: 300px;
      }
    </style>
    <script>
      function imageZoom(imgID, resultID) {
        var img, lens, result, cx, cy;
        img = document.getElementById(imgID);
        result = document.getElementById(resultID);
        /*create lens:*/
        lens = document.createElement("DIV");
        lens.setAttribute("class", "img-zoom-lens");
        /*insert lens:*/
        img.parentElement.insertBefore(lens, img);
        /*calculate the ratio between result DIV and lens:*/
        cx = result.offsetWidth / lens.offsetWidth;
        cy = result.offsetHeight / lens.offsetHeight;
        /*set background properties for the result DIV:*/
        result.style.backgroundImage = "url('" + img.src + "')";
        result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px";
        /*execute a function when someone moves the cursor over the image, or the lens:*/
        lens.addEventListener("mousemove", moveLens);
        img.addEventListener("mousemove", moveLens);
        /*and also for touch screens:*/
        lens.addEventListener("touchmove", moveLens);
        img.addEventListener("touchmove", moveLens);
        function moveLens(e) {
          var pos, x, y;
          /*prevent any other actions that may occur when moving over the image:*/
          e.preventDefault();
          /*get the cursor's x and y positions:*/
          pos = getCursorPos(e);
          /*calculate the position of the lens:*/
          x = pos.x - (lens.offsetWidth / 2);
          y = pos.y - (lens.offsetHeight / 2);
          /*prevent the lens from being positioned outside the image:*/
          if (x > img.width - lens.offsetWidth) {x = img.width - lens.offsetWidth;}
          if (x < 0) {x = 0;}
          if (y > img.height - lens.offsetHeight) {y = img.height - lens.offsetHeight;}
          if (y < 0) {y = 0;}
          /*set the position of the lens:*/
          lens.style.left = x + "px";
          lens.style.top = y + "px";
          /*display what the lens "sees":*/
          result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px";
        }
        function getCursorPos(e) {
          var a, x = 0, y = 0;
          e = e || window.event;
          /*get the x and y positions of the image:*/
          a = img.getBoundingClientRect();
          /*calculate the cursor's x and y coordinates, relative to the image:*/
          x = e.pageX - a.left;
          y = e.pageY - a.top;
          /*consider any page scrolling:*/
          x = x - window.pageXOffset;
          y = y - window.pageYOffset;
          return {x : x, y : y};
        }
      }
    </script>
  </head>
  <body>
    <h1>Image Zoom</h1>
    <p>Mouse over the image:</p>
    <div class="img-zoom-container">
      <img id="myimage" src="/uploads/media/default/0001/03/d670346cbbbda5cc6a629e275f87fd53d58ebc51.jpeg" width="300" height="240">
      <div id="myresult" class="img-zoom-result"></div>
    </div>
    <script>
      // Initiate zoom effect:

      imageZoom("myimage", "myresult");
    </script>
  </body>
</html>

Now let’s have a look at another example with a different lens:

Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF8">
    <title>Title of the document</title>
    <script src="https://unpkg.com/js-image-zoom@0.4.1/js-image-zoom.js" type="application/javascript"></script>
  </head>
  <body>
    <div id="img-container" style="width: 400px">
    <img src="https://assets.architecturaldesigns.com/plan_assets/324992268/large/23703JD_01_1553616680.jpg?1553616681" />
    <div>
    <script>
      var options = {
          width: 400,
          zoomWidth: 500,
          offset: {vertical: 0, horizontal: 10}
      };
      new ImageZoom(document.getElementById("img-container"), options);
       
    </script>
  </body>
</html>

Do you find this helpful?

Related articles