Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm trying to get a div element to follow my mouse (javascript), but it keeps glitching

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?

like image 852
HoneyPoop Avatar asked Oct 22 '25 19:10

HoneyPoop


1 Answers

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>
like image 64
Matt Croak Avatar answered Oct 25 '25 08:10

Matt Croak