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 the event.pageX
and event.pageY
are undefined.
The mousemove event occurs whenever the mouse pointer moves within the selected element. The mousemove() method triggers the mousemove event, or attaches a function to run when a mousemove event occurs. Note: Each time a user moves the mouse one pixel, a mousemove event occurs.
The pageX property returns the horizontal coordinate (according to the document) of the mouse pointer when a mouse event was triggered. The document is the web page. Tip: To get the vertical coordinate (according to the document) of the mouse pointer, use the pageY property. Note: This property is read-only.
To get the current mouse position we are going to trigger a mouse event. In this case we will use 'mousemove' to log the current X and Y coordinates of the mouse to the console. For a more detailed list of mouse events you could have a read of this.
The event. pageY property returns the position of the mouse pointer, relative to the top edge of the document. Tip: This event property is often used together with the event. pageX property.
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);
See it in jsFiddle.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With