0

I would like to ask you about help. I try to make a square that follows my mouse when I moving it, but something is wrong with my function and all the time after mouse move, the square is coming back to default position.

CODE:

let square = document.querySelector('.square')
let container = document.querySelector('.container')

container.addEventListener('mousemove', movingSquare);

function movingSquare(e) {
  square.style.transform = "translate" + "(" + e.offsetX + "px" + "," + e.offsetY + "px" + ")";
}
.container {
  background-color: red;
  height: 200px;
  width: 400px;
}

.square {
  background-color: blue;
  height: 50px;
  width: 50px;
}
<div class="container">
  <div class="square"> </div>
</div>
Rana
  • 2,500
  • 2
  • 7
  • 28

1 Answers1

0

The lagging error does not occur when you move up or left, but occurs when you move down or right, this occurs when you move down or right, the containers mousemove event, doesn't get activated instead, the square receives the event, as when you move right/down your mouse falls on cursor

The below example is how your problem should look

let square = document.querySelector('.square')
let container = document.querySelector('.container')
container.addEventListener('mousemove', movingSquare);
function movingSquare(e) {
  square.style.transform = "translate" + "(" + e.offsetX + "px" + "," + e.offsetY + "px" + ")";
}
.container {
  background-color: red;
  height: 200px;
  width: 400px;
}

.square {
  background-color: blue;
  height: 50px;
  width: 50px;
}
<div class="container">
  <div class="square"> </div>
</div>

Solution

The square receives the event because it has pointer-events auto(true).
You can disable this in css by using pointer-events:none;

See the snippet below

let square = document.querySelector('.square')
let container = document.querySelector('.container')
container.addEventListener('mousemove', movingSquare);
function movingSquare(e) {
  square.style.transform = "translate" + "(" + e.offsetX + "px" + "," + e.offsetY + "px" + ")";
}
.container {
  background-color: red;
  height: 200px;
  width: 400px;
}

.square {
  background-color: blue;
  height: 50px;
  width: 50px;
  pointer-events: none;/*ADDED THIS LINE*/
}
<div class="container">
  <div class="square"> </div>
</div>

Refer here

Neptotech -vishnu
  • 1,096
  • 8
  • 23