Home > Software design >  How to return the current and previous value of the mouse coordinate?
How to return the current and previous value of the mouse coordinate?

Time:11-11

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.

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;
    });
};

CodePudding user response:

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;
    });
};

  • Related