Is there a way to trigger mousemove and get event.pageX, event.pageY?
Solution 1
I don't believe it possible to get the mouse coordinates on demand via JavaScript / jQuery; however if you bind the position to a global var you can then access them at anytime throughout the document like this:
$(document).ready(function(){
$().mousemove(function(e){
window.xPos = e.pageX;
window.yPos = e.pageY;
});
});
for a less CPU intensive option, you can add a timeout, although you trade performance for a slight delay in knowing where the mouse is:
function getMousePosition(timeoutMilliSeconds) {
$(document).one("mousemove", function (event) {
window.xPos = event.pageX;
window.yPos = event.pageY;
setTimeout("getMousePosition(" + timeoutMilliSeconds + ")", timeoutMilliSeconds);
});
}
getMousePosition(100);
You should now be able to access the window.xPos and window.yPos from anywhere in the document using either solution without needing to trigger a faux event.
Solution 2
You need to set pageX
and pageY
directly before triggering the event. To set these properties, make a jQuery.Event
object.
// create a jQuery event
e = $.Event('mousemove');
// set coordinates
e.pageX = 100;
e.pageY = 100;
// trigger event - must trigger on document
$(document).trigger(e);
Geo P
Updated on July 22, 2022Comments
-
Geo P almost 2 years
So, like the question specifies, is there a way to trigger a
mousemove
event in jQuery which also sends the mouse coordinates to the event Object?So far my code can trigger the
mousemove
using the.trigger(event)
function but theevent.pageX
andevent.pageY
are undefined.