9

OK, this works perfectly fine for following my mouse.

//
$(document).mousemove(function(e){
  $("#follower").css({
      'top': e.pageY + 'px';
      'left': e.pageX + 'px';
  });
});
//

And this works great for animating the mouse to a clicked point

//
$(document).click(function(e){
  $("#follower").animate({
      top: e.pageY + 'px';
      left: e.pageX + 'px';
  }, 800);
});
//

But I personally feel that logically this SHOULD work! Coming from my point of view as the webscripter. Amd then my question is, how can I make this work. I want the #follower to try and follow my mouse with a dynamic kind of lagging behind feel.

//
$(document).mousemove(function(e){
  $("#follower").animate({
      top: e.pageY + 'px';
      left: e.pageX + 'px';
  }, 800);
});
//
Zevan
  • 10,097
  • 3
  • 31
  • 48
Joshua Robison
  • 1,868
  • 4
  • 20
  • 24

1 Answers1

33

How about using setInterval and an equation called zeno's paradox:

http://jsfiddle.net/88526/1/

That's the way I usually do it.

As requested, I've included the code in this answer. Given a div with absolute positioning:

CSS:

#follower{
  position : absolute;
  background-color : red;
  color : white;
  padding : 10px;
}

HTML:

<div id="follower">Move your mouse</div>

JS w/jQuery:

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);
Zevan
  • 10,097
  • 3
  • 31
  • 48
  • thanks Zevan, I'm gonna try that right now. If I have trouble with the equation I'll be back :) – Joshua Robison Jan 31 '11 at 07:24
  • Wow, you did it all for me. You're the man. It might be nice for the community if this answer is posted directly into SO. Would you mind if I edited your answer to include this? – Joshua Robison Jan 31 '11 at 07:26
  • @Zevan the fiddle appears to be broken. – maxshuty Mar 06 '17 at 20:14
  • 1
    @Zevan - strange. It was definitely broken before, must have been something with jsFiddle itself. But you are right, it is working now. :) – maxshuty Mar 20 '17 at 12:21