Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda