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
You can use jQuery's .offset() to get the position of the element relative to the document, then subtract its left and top from the e.pageX and e.pageY values, respectively.
To ensure it stays within the box, you need a lower bound on the mouseX and mouseY values. You could use Math.max or the ifs like I used below.
$(window).mousemove(function(e){
var offset = $('.container').offset();
mouseX = Math.min(e.pageX - offset.left, limitX);
mouseY = Math.min(e.pageY - offset.top, limitY);
if (mouseX < 0) mouseX = 0;
if (mouseY < 0) mouseY = 0;
});
JSFiddle demo