How to get mouse position in jQuery without mouse-events?
I don't believe there's a way to query the mouse position, but you can use a mousemove
handler that just stores the information away, so you can query the stored information.
jQuery(function($) {
var currentMousePos = { x: -1, y: -1 };
$(document).mousemove(function(event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
// ELSEWHERE, your code that needs to know the mouse position without an event
if (currentMousePos.x < 10) {
// ....
}
});
But almost all code, other than setTimeout
code and such, runs in response to an event, and most events provide the mouse position. So your code that needs to know where the mouse is probably already has access to that information...
You can't read mouse position in jQuery without using an event. Note firstly that the event.pageX
and event.pageY
properties exists on any event, so you could do:
$('#myEl').click(function(e) {
console.log(e.pageX);
});
Your other option is to use a closure to give your whole code access to a variable that is updated by a mousemove handler:
var mouseX, mouseY;
$(document).mousemove(function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
}).mouseover(); // call the handler immediately
// do something with mouseX and mouseY