Zoom Box

Overflow hidden html container that moves with cursor.

by jruddell

HTML

<div style="color:#FFFFFF;background:#102030;text-align:center;">
    <h1 style="text-align:center;">Test Move Background on Mousemove:</h1>
    <div id="viewer">
        <div>
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
            test <br />
        </div>
    </div>
    <input type="text" id="xy" />
    <input type="text" id="scroll" />
</div>

CSS

#viewer {border:solid 1px #FFFFFF;margin:50px auto 0px auto;width:400px;height:400px;overflow:hidden;position:relative}

#viewer div {background: url(http://background-wallpaper.110mb.com/images/Wallpapers1280/computer-backgrounds/tunnel-background.jpg) 0 0 no-repeat; width:1280px;height:1024px;}

input[type="text"] {display:block;margin:10px auto;width:100px;}

JavaScript

$(document).ready(function(){
    var viewer = $('#viewer'),
        vH = viewer.height(),
        vW = viewer.width(),
        vT = viewer.offset().top,
        vL = viewer.offset().left,
        sTop = viewer.find(':first').height() + 18 - vH,
        sLeft = viewer.find(':first').width() + 18 - vW;
    
    $('#viewer').mousemove(function(e){
        var $this = $(this),
            y = (e.pageY-vT)/vH,
            x = (e.pageX-vL)/vW;
           
        $('#xy').val(x+' , '+y);
        $('#scroll').val(Math.round(sLeft * x)+' , '+Math.round(sTop * y));
        $this.scrollTop(Math.round(sTop * y)).scrollLeft(Math.round(sLeft * x));
    });
});