Skip to content
Advertisement

Zoom still show original image after switching new image from thumbnail

I use Image Zoom from w3schools, code as follows:

function imageZoom(imgID, resultID) {
  var img, lens, result, cx, cy;
  img = document.getElementById(imgID);
  result = document.getElementById(resultID);
  lens = document.createElement("DIV");
  lens.setAttribute("class", "img-zoom-lens");
  img.parentElement.insertBefore(lens, img);
  cx = result.offsetWidth / lens.offsetWidth;
  cy = result.offsetHeight / lens.offsetHeight;
  result.style.backgroundImage = "url('" + img.src + "')";
  result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px";
  lens.addEventListener("mousemove", moveLens);
  img.addEventListener("mousemove", moveLens);
  lens.addEventListener("touchmove", moveLens);
  img.addEventListener("touchmove", moveLens);
  result.style.display = "none";

  function moveLens(e) {
    var pos, x, y;
    e.preventDefault();
    pos = getCursorPos(e);
    x = pos.x - (lens.offsetWidth / 2);
    y = pos.y - (lens.offsetHeight / 2);
    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;}
    lens.style.left = x + "px";
    lens.style.top = y + "px";
    result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px";
  }

  function getCursorPos(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};
  }
}

imageZoom("myimage", "myresult");

And I use the following simple code to switch images:

function change_img(img_src) {
  document.getElementsByName("goods_img")[0].src=img_src;
}

My url: https://cn.angelcorp.net/shop/goods.php?id=9 You may click the thumbnail image with flag, but the zoom still show original image without flag. Thank you.

Advertisement

Answer

You’ve got to change the background of myresult to the img_src as well. Change the function to this

function change_img(img_src) {
document.getElementsByName("goods_img")[0].src=img_src;
document.getElementById("myresult").style = `background-image: url("${img_src}"); background-size: 468.846px 468.846px; display: none; background-position: -256.846px -256.846px;`;
}
Advertisement