Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda