Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!