jQuery image panning within a container

by lasha

HTML

<div class="container">
    <img src="http://placekitten.com/g/500/300">
</div>

<span class="zoomIn">zoom in</span>
<span class="zoomOut">zoom out</span>

CSS

.container {
    position: relative;
    width: 500px;
    height: 300px;
    background: #ccc;
/*     margin-top: 50px;
    margin-left: 100px; */
    cursor: pointer;
    overflow: hidden;
}

img {
    position: absolute;
    left: 0;
    top: 0;
    min-width: 100%;
    height: auto;
}

JavaScript

var $container = $(".container"),
    containerWidth = $container.width(),
    containerHeight = $container.height();

var $containerImg = $container.find("img"),
    containerImgWidth = $containerImg.width(),
    containerImgHeight = $containerImg.height();
    
var offset = $container.offset();

$container.mousemove(function(e){
  var offsetLeft = e.pageX - offset.left;
  var offsetTop = e.pageY - offset.top;
  panImage(offsetLeft, offsetTop);
});

var panTimer;

function panImage(left, top){
    //$("span:first").text("" + left + " " + top);
    /*$containerImg.css("left", function(){
        return -(left / containerWidth) * (containerImgWidth - containerWidth);
    });
    $containerImg.css("top", function(){
        return -(top / containerHeight) * (containerImgHeight - containerHeight);
    });*/
    
    clearTimeout(panTimer);
    panTimer = setTimeout(function(){
        $containerImg.stop().animate({
            left: -(left / containerWidth) * (containerImgWidth - containerWidth),
            top: -(top / containerHeight) * (containerImgHeight - containerHeight)
        }, 70, "linear");
    },10);
}

$(".zoomIn").on("click", function(e){
    var img = $(document.createElement('img'))
    img.addClass("zoomedImg");
    img.attr('src', "http://placekitten.com/g/1000/700");
    img.load(function(){
        $(this).appendTo($container);
        
            $container = $(".container"),
            containerWidth = $container.width(),
            containerHeight = $container.height();
        
            $containerImg = $container.find(".zoomedImg"),
            containerImgWidth = $containerImg.width(),
            containerImgHeight = $containerImg.height();
    });
});