JavaScript / jQuery - Follow the cursor with a DIV
-
- 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:
- With jQuery, the same Div and CSS style, but with this code:
You can apply position "absolute" or "fixed" to the #div_moving in CSS.
- 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.
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>
- 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
- Hour and Minutes togheter in Javascript
JavaScript - jQuery - Ajax First post
Dear Coursesweb I can not find out how to add the hours + minutes togheter.Last post
<SCRIPT LANGUAGE= JavaScript >
day = new Date()
hr =...
See and use the following example:
<script>
var day = new Date();
let hr = day.getHours();
let mn = day.getMinutes();
let se =... - Display message to every minute in Javascript
JavaScript - jQuery - Ajax First post
Hello,Last post
On eatch minute from the current hour I wanna have an message
I can not find out how to complete
I hope to get something like this (code...
If you only want to display a message to every minute, just use the setInterval() function. It calls a function repeatedly, over and over again, at...