user1408440
user1408440

Reputation: 217

How can I use jQuery to follow the cursor with a div?

I have a div in the shape of a circle that follows your mouse using Javascript, but I want it to stop when it hits the edge of a container div. How would I do that? Here is the Javascript im using:

var mouseX = 0, mouseY = 0;
$(document).mousemove(function(e){
mouseX = e.pageX;
mouseY = e.pageY;
});

// 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);

and here is everything else I have so far: jsFiddle

Please help, and thanks!

Upvotes: 2

Views: 2459

Answers (1)

methodofaction
methodofaction

Reputation: 72465

You need to establish the limits of the element that moves...

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);
});

Where 150 is the width/height of your container, and 15 is the size of your cursor

http://jsfiddle.net/fhmkf/

Upvotes: 3

Related Questions