'How to move a doom element to the mouse position in a second regardless of their positions on the screen
https://codepen.io/DraguLL/pen/gOXmJgo hello everyone, how to change the code so that the square moves to the mouse position in exactly one second, no matter where it is and where the mouse position is
const myElement = document.getElementById('cir');
let x = 0;
let y = 0;
let xMouse = 0;
let yMouse = 0;
window.addEventListener('mousemove', e => {
xMouse = e.clientX;
yMouse = e.clientY;
});
setInterval(() => {
if (xMouse === x && yMouse === y) {
x = xMouse;
y = yMouse;
} else {
if (xMouse > x) {
x++;
} else {
x--;
}
if (yMouse > y) {
y++;
} else {
y--;
}
}
myElement.style.top = y + 'px';
myElement.style.left = x + 'px';
}, 1);
.cir {
position: fixed;
background: red;
top: 10px;
left: 10px;
width: 10px;
height: 10px;
}
<div class ="cir" id = "cir"></div>
Solution 1:[1]
You can use setTimeout and then use CSS transition to make that smooth effect of red dot moving.
const myElement = document.getElementById('cir');
let x = 0;
let y = 0;
let xMouse = 0;
let yMouse = 0;
let timer;
window.addEventListener('mousemove', e => {
xMouse = e.clientX;
yMouse = e.clientY;
clearTimeout(timer);
timer = setTimeout(mouseMove, 1000);
});
function mouseMove() {
x = xMouse;
y = yMouse;
myElement.style.transition = "1s ease";
myElement.style.top = y + 'px';
myElement.style.left = x + 'px';
}
.cir {
position: fixed;
background: red;
top: 10px;
left: 10px;
width: 10px;
height: 10px;
}
<div class ="cir" id = "cir"></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ali Mustafa |
