Page 1 of 1

JavaScript / jQuery - Follow the cursor with a DIV

Posted: 22 Jan 2015, 14:30
by PloMar
How can I use JavaScript /jQuery to follow the mouse cursor with a DIV in the whole page?

JavaScript / jQuery - Follow the cursor with a DIV

Posted: 22 Jan 2015, 14:44
by Admin
If you want this effect with pure JavaScript, you can use this code:

Code: Select all

<style>
#div_moving {
  position: absolute;
  width: 140px;
  height: 65px
  margin: 0;
  border: 1px solid #33f;
  background: #88ee99;
}
</style>

<div id="div_moving">Some content ..</div>
<script>
var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp = 0;
var div_moving = document.getElementById('div_moving');

document.addEventListener('mousemove', function(e){
  $mouseX = e.clientX;
  $mouseY = e.clientY;    
});

var $loop = setInterval(function(){
  // change 5 to alter damping higher is slower
  $xp += (($mouseX - $xp)/5);
  $yp += (($mouseY - $yp)/5);
  div_moving.style.left = $xp +'px';
  div_moving.style.top = $yp +'px';
}, 60);
</script>
- With jQuery, the same Div and CSS style, but with this code:

Code: Select all

<script>
var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp =0;

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

var $loop = setInterval(function(){
  // change 5 to alter damping higher is slower
  $xp += (($mouseX - $xp)/5);
  $yp += (($mouseY - $yp)/5);
  $('#div_moving').css({left:$xp +'px', top:$yp +'px'});
}, 60);
</script>
You can apply position "absolute" or "fixed" to the #div_moving in CSS.
- Demo of these codes is the green rectangle that follows your mouse cursor.
Some content ..

- If you want the moving Div to follow the mouse inside a parent, you can use the code from this page: Follow the mouse cursor with a DIV inside a Parent.