Follow Mouse Cursor within the Container

by naga raju

HTML

<div class="centerdiv" style="position:relative; margin-top:21px; margin-left:21px;">
    <div class="container">
        <div id="follower"></div>
    </div>
</div>

CSS

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

/*.centerdiv {
    width:150px;
    margin-left:auto;
    margin-right:auto;
    position:relative;
}*/

.centerdiv:hover #follower { display:block; }

.container
{
    width:150px;
    height:150px;   
    position:absolute;
    top:0;
    left:0;
    overflow:hidden;
    border:1px solid #000000;
}

JavaScript

var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15;
$('.container').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;
   console.log(mouseX + ' ' + mouseY);
});

// 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;
    console.log(xp + ' ' + yp);
    follower.css(
    		{left:xp-1, top:yp-1}
    );
}, 0);