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.
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>
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
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>
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>