I have followed some wonderful code to have an image follow the mouse cursor within a div container at http://jsfiddle.net/fhmkf/. The problem is, this method only works for div containers fixed in absolute left/top position and relies on e.pageX and e.pageY coordinates.
I need to position my div in the center of the page or nest it in a div centered.
When I try to attempt to proceed centering the div, its screws up the mouse cursor and image. The object will only move with I have the mouse up in the upper left hand corner of the browser (because its using e.pageX and e.pageY coordinates)
Here is my code. JavaScript
var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15;
$(window).mousemove(function(e){
mouseX = Math.min(e.pageX, limitX);
mouseY = Math.min(e.pageY, limitY);
});
// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping higher is slower
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.css({left:xp, top:yp});
}, 30);
My CSS
.centerdiv {
width:150px;
margin-left:auto;
margin-right:auto;
position:relative;
}
#follower{
position : relative;
background-color : yellow;
width:15px;
height:15px;
border-radius:50px;
}
.container
{
width:150px;
height:150px;
position:absolute;
top:0;
left:0;
overflow:hidden;
border:1px solid #000000;
}
My HTML
<div class="centerdiv">
<div class="container">
<div id="follower"></div>
</div>
</div>
I created an FSFiddle to show you what happens (notice you can only move the object when you have the cursor to the left and top edge of the page). http://jsfiddle.net/3964w/
I believe its related to e.PageX and e.PageY and I saw somewhere to use e.ClientX and e.ClientY but I don't know how.
Thank you.