JavaScript / jQuery - Follow the cursor with a DIV
Posted: 22 Jan 2015, 14:30
How can I use JavaScript /jQuery to follow the mouse cursor with a DIV in the whole page?
Web Development and Programming Courses
https://coursesweb.net/forum/
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>
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>