<!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;
width: 40px;
height: 40px;
}
.img-zoom-result {
border: 1px solid #d4d4d4;
width: 300px;
height: 300px;
}
</style>
<script>
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);
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};
}
}
</script>
</head>
<body>
<h1>Image Zoom</h1>
<p>Mouse over the image:</p>
<div class="img-zoom-container">
<img id="myimage" src="img_girl.jpg" width="300" height="240">
<div id="myresult" class="img-zoom-result"></div>
</div>
<p>The image must be placed inside a container with relative positioning.</p>
<p>The result can be put anywhere on the page, but must have the class name "img-zoom-result".</p>
<p>Make sure both the image and the result have IDs. These IDs are used when a javaScript initiates the zoom effect.</p>
<script>
imageZoom("myimage", "myresult");
</script>
</body>
</html>