JavaScript / jQuery - Follow the cursor with a DIV

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts: 48

JavaScript / jQuery - Follow the cursor with a DIV

How can I use JavaScript /jQuery to follow the mouse cursor with a DIV in the whole page?

Admin Posts: 805
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.

Similar Topics