I have been trying to get a div element to follow my mouse with javascript, but it keeps glitching to the upper left hand corner. Here is my code: HTML:
<html>
<body>
<div id="circle"></div>
</body>
</html>
CSS:
body{
margin:0;
padding:0;
overflow:hidden;
background-color:#77dd77;
}
div{
position:absolute;
transform:translate(-50%,-50%);
height:35px;
width:35px;
border-radius:50%;
border:2px solid black;
}
JavaScript:
document.addEventListener('mousemove', function(e) {
let body = document.querySelector('body');
let circle = document.getElementById('circle');
let left = e.offsetX;
let top = e.offsetY;
circle.style.left = left + 'px';
circle.style.top = top + 'px';
});
I'm still having a hard time figuring out if the error is occuring in the CSS or JavaScript. Can someone help?
You should use e.pageY and e.pageX instead of e.offset... because page... is relative to the document as a whole. offset... is relative to the parent container (in this case body) and since body has no height (since it's child has a position of absolute) the mouse detection for offset... is inconsistent.
let circle = document.getElementById('circle');
const onMouseMove = (e) =>{
circle.style.left = e.pageX + 'px';
circle.style.top = e.pageY + 'px';
}
document.addEventListener('mousemove', onMouseMove);
body{
margin:0;
padding:0;
overflow:hidden;
background-color:#77dd77;
}
#circle{
position:absolute;
transform:translate(-50%,-50%);
height:35px;
width:35px;
border-radius:50%;
border:2px solid black;
}
<html>
<body>
<div id="circle"></div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With