Magnifier

by Alice Farmer

HTML

<div id="container">    
    <img src="https://upload.wikimedia.org/wikipedia/en/9/9f/Madokacharacters.jpg">
    <img src="https://upload.wikimedia.org/wikipedia/en/f/fc/MadokaBD.jpg">
    <img src="https://upload.wikimedia.org/wikipedia/en/f/fc/MadokaBD.jpg" height="256px">
    <div id="magnifier"></div>
</div>

CSS

#magnifier {
    visibility: hidden;
    width: 256px;
    height: 256px;
    position: absolute;
    border: 1px solid grey;
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 50%;
    background-repeat: no-repeat;
    pointer-events:none;
}
* {
    margin: 0;
    padding: 0;
}
img {
    margin: 64px;
}
#container {
    width: 100%;
    height: 100%;
}

JavaScript

(function() {
    "use strict";
    var magY, magX, magShown = 0, imgPath = "none", zoom = 500, zoomFactor = zoom / 100, pWidth = 0, pHeight = 0, pOffset = 0, magZ = false;
    var updater = window.setInterval(update, 100);
    $(document).mousemove(function(e) {
        magY = e.pageY;
        magX = e.pageX;
        $('#magnifier').offset({ top: magY - ($('#magnifier').height() / 2), left: magX - ($('#magnifier').width() / 2) });
        imgPath = e.target.src || "none";
        var backLeft = ((-magX + pOffset.left) * zoomFactor) + pWidth - ($('#magnifier').width() / 1.5);
        var backTop = ((-magY + pOffset.top) * zoomFactor) + pHeight - ($('#magnifier').height());
        $('#magnifier').css("background-position", backLeft + "px " + backTop + "px");
    });
    $(document).mousedown(function(e) {
        if (e.which == 2) {
            e.preventDefault();
            magnifier();
        }
    });
    $(document).keydown(function(e) {
        if (e.which == 90) {
            e.preventDefault();
            magZ = true;
        } else {
            magZ = false;
        }
        if (magZ === true) {
            magnifier();
        }
    });

    function magnifier() {
        magShown = magShown ? 0 : 1;
        if (magShown == 1) {
            $('#magnifier').css("visibility", "visible");
            $('#container').css("cursor", "none");
        } else {
            $('#magnifier').css("visibility", "hidden");
            $('#container').css("cursor", "auto");
        }
    }
    $('img').mousemove(function(e){
        pOffset = $(this).offset();
        pWidth = $(this).width();
        pHeight = $(this).height();
    });
    function update() {
        if (imgPath !== "none") {
            imgPath = imgPath.replace(/<img src=\"(.+)\">/, '$1');
            $('#magnifier').css("background-image", "url(" + imgPath + ")");
            $('#magnifier').css("background-size", (pWidth * zoomFactor) + "px " + (pHeight * zoomFactor) + "px");
        }
   ...