Search code examples
javascriptjqueryjquery-eventsmousemoveonmousemove

Issue with Image movement on mousemove (in opposite direction)


I have to move an image using jQuery / Javascript exactly like this url

I have done similar to this using my own logic. But it gets cut for smaller / bigger image either at the top or at the bottom. Or It moves completely at the bottom and doesn't move completely at the top or vice-versa.

http://jsfiddle.net/N2k6M/ (Please move the horizontal scrollbar to view full image.)

Can anyone please suggest me / Fix my code here, so that my mousemove functionality works perfectly fine and upper / lower part of image moves properly.

I need a seamless movement of image just like in the original url.

HTML PART

<div id="oheight" style="z-index:1000;position:absolute;">123</div> , <div id="yheight" style="z-index:1000;position:absolute;">123</div>

    <img id="avatar" src="http://chaikenclothing.com/wp-content/uploads/2012/05/11.jpg![enter image description here][2]" style="position:absolute;overflow:hidden;" />

JAVASCRIPT PART

<script src="http://code.jquery.com/jquery-latest.js"></script> 
<script lang="javascript">
var doc_height = $(document).height();
function updateAvatarPosition( e )
{
    var avatar = document.getElementById("avatar");
    var yheight = parseInt(e.y);
    var ywidth = e.x;
    //avatar.style.left = e.x + "px";
    
    
    if((yheight)<(doc_height)){     
        yheight*=2;
        avatar.style.top = '-'+(yheight) + "px";
    }
    console.log(yheight);
    $("#oheight").html(doc_height);
    $("#yheight").html(yheight);
    /*if((ywidth)<(doc_height/6)){
        avatar.style.top = '-'+e.x + "px";
    }*/ 
}

document.getElementById("avatar").onmousemove = updateAvatarPosition;


</script>

Solution

  • see http://jsfiddle.net/N2k6M/7/

    function updateAvatarPosition( e )
    {
        var img_height = $('#avatar').height();
        var window_height = $(window).height();
        var factor = (img_height - window_height) / window_height;
        if(factor > 1) {
            var avatar = document.getElementById("avatar");
            var yheight = parseInt(e.clientY);
            avatar.style.top = '-'+(yheight * factor) + "px";    
        }
    }