Create an Image Zoom Window with Javascript

CSS

<style>
#container {
    position: relative;
}

#zoomwindow {
    position: absolute;
    border: 1px solid #fff;
    width: 100px;
    height: 100px;
    visibility: hidden;
    border-radius: 4px;
}

#image, #zoomimage {
    width: 300px;
    height: 303px;
    border: thin gray solid;
    border-radius: 4px;
    display: inline-block;
}
</style>

HTML

<div id="container">
    <div id="zoomwindow"></div>
    <img id="image" src="../images/sunset.jpg">
    <div id="zoomimage"></div>
</div>

Javascript

<script>
(function() {
    img = document.getElementById("image");
    img.addEventListener("mousemove", moveView);
    zoomwindow = document.getElementById("zoomwindow");
    zoomwindow.addEventListener("mousemove", moveView);
    zoomimage = document.getElementById("zoomimage");
    oW = zoomimage.offsetWidth / zoomwindow.offsetWidth;
    oH = zoomimage.offsetHeight / zoomwindow.offsetHeight;
    zoomimage.style.backgroundImage = "url(../images/sunset.jpg)";
    zoomimage.style.backgroundSize = (img.width * oW) + "px " + (img.height * oH) + "px";

    function moveView(e) {
        e.preventDefault();
        e = e || window.event;
        zoomwindow.style.visibility = "visible";
        bounds = img.getBoundingClientRect();
        x = e.pageX - bounds.left - window.pageXOffset - (zoomwindow.offsetWidth / 2);
        if (x > img.width - zoomwindow.offsetWidth) {x = img.width - zoomwindow.offsetWidth;}
        if (x < 0) {x = 0;}
        zoomwindow.style.left = x + "px";
        y = e.pageY - bounds.top - window.pageYOffset - (zoomwindow.offsetHeight / 2);
        if (y > img.height - zoomwindow.offsetHeight) {y = img.height - zoomwindow.offsetHeight;}
        if (y < 0) {y = 0;}
        zoomwindow.style.top = y + "px";
        zoomimage.style.backgroundPosition = "-" + (x * oW) + "px -" + (y * oH) + "px";
    }
})();
</script>

Example:

Mouse over the image to zoom in on the cursor location.

Copyright © Lage.us Website Development | Disclaimer | Privacy Policy | Terms of Use