0

I'm trying to get mouse cursor current position at frequent interval.

function checkMousePos(ev){
            alert(true);
            var x = ev.clientX,
            y = ev.clientY;
            alert('' + x + ' ' + y);
}

setInterval(checkMousePos, 500);

This code alerts true, but never x and y.

What am I not doing right ?

1 Answers1

1

When debugging something you far better using something like console.log(myVariable) and then viewing it in the console. In your case ev not being pass by your interval and there for it's undefined. What seems like this:

var x;
var y;

document.addEventListener('mousemove', function(event){
    x = event.pageX;
    y = event.pageY;
})

function checkMousePos(){
    console.log("Cursor at: " + x + ", " + y);
}

setInterval(checkMousePos, 500);

Although it's usually not the best solution.

  • Not in relation to your answer but in regard to your output location. If I am doing a quick bit of debugging I still throw things out to document.title. It's a bit old school but it stops you needing to swap between the browser and the dev tools (normally where the console exists) to see the result. – Ric Mar 25 '19 at 17:28
  • Thank you Alex. This results in Cursor at: undefined, undefined. –  Mar 25 '19 at 17:30