Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return the current and previous value of the mouse coordinate?

On the below code, onmousemove is checking the coordinate X and Y of the mouse travelling. And then I return inside myInterval the coordinate X and Y at the end of 1 second. My intention is to know where the customer’s mouse is every second.

let latestX;
let latestY;

let previousX;
let previousY;  

let mouseHasMoved = false;
DEFAULT_INTERVAL = 2000;

onmousemove = () => {
    window.addEventListener('mousemove', (e)=> {
        latestX = e.x
        latestY = e.y
        mouseHasMoved = true;
    });
};


myInterval = setInterval(()=> {
    if (mouseHasMoved) {
        mouseHasMoved = false;
        console.log(`x: ${latestX}, y: ${latestY}`)
    }
}, DEFAULT_INTERVAL);

I want to expand the above code to also show me the previous coordinate, using previousX and previousY.

Let’s say my current coordinates are X: 10 and Y: 20.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, initially previousX and previousY would be undefined and latestX: 10 and latestY: 20. After I change my mouse coordinate; X: 10 and Y: 20 would be assigned to previousX and previousY, and latestX and latestY would have new values.

I have tried assigning the values as below, but it didn’t work. Both previous and latest had the same values:

onmousemove = () => {
    window.addEventListener('mousemove', (e)=> {
        previousX = latestX;
        previousY = latestY;
        
        latestX = e.x
        latestY = e.y
        mouseHasMoved = true;
    });
};

>Solution :

The problem is that you assign the previousX and previousY values in the mouse move handler. If you move this to the interval handler, it will work as expected:

let latestX;
let latestY;

let previousX;
let previousY;  

let mouseHasMoved = false;
DEFAULT_INTERVAL = 2000;

myInterval = setInterval(()=> {
    if (mouseHasMoved) {
        mouseHasMoved = false;
        console.log(`prevX: ${previousX}, prevY: ${previousY}, x: ${latestX}, y: ${latestY}`);
        previousX = latestX;
        previousY = latestY;
    }
}, DEFAULT_INTERVAL);

onmousemove = () => {
    window.addEventListener('mousemove', (e)=> {
        latestX = e.x
        latestY = e.y
        mouseHasMoved = true;
    });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading